Parsing JSON Within JSON in Objective-C

Read Json Response from server and parse in objective-c xcode

I solved the issue with following code.

 NSMutableDictionary *jsondata = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSMutableArray *jsonfname = [[jsondata objectForKey:@"data"] objectForKey:@"first_name"];
NSMutableArray *jsonlname = [[jsondata objectForKey:@"data"] objectForKey:@"last_name"];

Parsing JSON to a predefined class in Objective C

Instead of using dictionaries directly you can always deserialize (parse) JSON to your class with using Key-value coding. Key-value coding is a great feature of Cocoa that lets you access properties and instance variables of class at runtime by name. As I can see your JSON model is not complex and you can apply this easily.

person.h

#import <Foundation/Foundation.h>

@interface Person : NSObject

@property NSString *personName;
@property NSString *personMiddleName;
@property NSString *personLastname;

- (instancetype)initWithJSONString:(NSString *)JSONString;

@end

person.m

#import "Person.h"

@implementation Person

- (instancetype)init
{
self = [super init];
if (self) {

}
return self;
}

- (instancetype)initWithJSONString:(NSString *)JSONString
{
self = [super init];
if (self) {

NSError *error = nil;
NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *JSONDictionary = [NSJSONSerialization JSONObjectWithData:JSONData options:0 error:&error];

if (!error && JSONDictionary) {

//Loop method
for (NSString* key in JSONDictionary) {
[self setValue:[JSONDictionary valueForKey:key] forKey:key];
}
// Instead of Loop method you can also use:
// thanks @sapi for good catch and warning.
// [self setValuesForKeysWithDictionary:JSONDictionary];
}
}
return self;
}

@end

appDelegate.m

@implementation AppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {

// JSON String
NSString *JSONStr = @"{ \"personName\":\"MyName\", \"personMiddleName\":\"MyMiddleName\", \"personLastname\":\"MyLastName\" }";

// Init custom class
Person *person = [[Person alloc] initWithJSONString:JSONStr];

// Here we can print out all of custom object properties.
NSLog(@"%@", person.personName); //Print MyName
NSLog(@"%@", person.personMiddleName); //Print MyMiddleName
NSLog(@"%@", person.personLastname); //Print MyLastName
}

@end

The article using JSON to load Objective-C objects good point to start.

JSON Parsing in Objective-C

You are doing it wrong. You have filled your JSON Data in your Dictionary (named json) correctly. But then you have an Array of Dictionaries (called Albumvideo) inside your Main Dictionary and value of titre is inside Albumvideo Array.

The Correct Code is :

NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* albumsvideo = [json objectForKey:@"Albumvideo"];
NSString *titre1 = [[albumsvideo objectAtIndex:0]valueForKey:@"titre"];
NSString *titre2 = [[albumsvideo objectAtIndex:1]valueForKey:@"titre"];

Understand the Concept. It depends on what you have inside your JSON. If it's an Array ( Values inside [ ]) then you have to save in NSArray, if it's a Dictionary ( Values inside { }) then save as NSDictionary and if you have single values like string , integer, double then you have to save them using appropriate Objective-C Data types.

Hope, you got some proper idea about JSON Parsing.

objective-c json parser: How to parse a json file starting with a string and not brackets?

I assume that you want to strip the method call and keep only the passed JSON argument. If you're sure that the file contains only a method call, and no other code, especially one with curly braces, you can apply the following logic: find the first and the last curly brace, and use that substring:

NSString *dataString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSUInteger firstCurlyBracePos = [dataString rangeOfString:@"{" options:0].location;
NSUInteger lastCurlyBracePos = [dataString rangeOfString:@"}" options: NSBackwardsSearch].location;
NSString jsonString = nil;
if(firstCurlyBracePos != NSNotFound && lastCurlyBracePos != NSNotFound) {
jsonString = [dataString substringWithRange:NSMakeRange(firstCurlyBracePos, lastCurlyBracePos-firstCurlyBracePos)];
}

jsonString will hold the JSON part of the file, or nil if at least one of the two curly braces was not found.

Read JSON file in Objective C

Just drag your JSON file into the project navigator pane in Xcode so it appears in the same place as your class files.

Make sure to select the 'Copy items if needed' tick box, and add it to the correct targets.

Then do something like this:

- (void)doSomethingWithTheJson
{
NSDictionary *dict = [self JSONFromFile];

NSArray *colours = [dict objectForKey:@"colors"];

for (NSDictionary *colour in colours) {
NSString *name = [colour objectForKey:@"name"];
NSLog(@"Colour name: %@", name);

if ([name isEqualToString:@"green"]) {
NSArray *pictures = [colour objectForKey:@"pictures"];
for (NSDictionary *picture in pictures) {
NSString *pictureName = [picture objectForKey:@"name"];
NSLog(@"Picture name: %@", pictureName);
}
}
}
}

- (NSDictionary *)JSONFromFile
{
NSString *path = [[NSBundle mainBundle] pathForResource:@"colors" ofType:@"json"];
NSData *data = [NSData dataWithContentsOfFile:path];
return [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
}

In iOS, how do I parse a JSON string into an object

You can do it like

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:responseObject options:0 error:&error];//response object is your response from server as NSData

if ([json isKindOfClass:[NSDictionary class]]){ //Added instrospection as suggested in comment.
NSArray *yourStaffDictionaryArray = json[@"directory"];
if ([yourStaffDictionaryArray isKindOfClass:[NSArray class]]){//Added instrospection as suggested in comment.
for (NSDictionary *dictionary in yourStaffDictionaryArray) {
Staff *staff = [[Staff alloc] init];
staff.id = [[dictionary objectForKey:@"id"] integerValue];
staff.fname = [dictionary objectForKey:@"fName"];
staff.lname = [dictionary objectForKey:@"lName"];
//Do this for all property
[yourArray addObject:staff];
}
}
}

Parsing JSON Within JSON in Objective-C

What you have in reality:
Classic JSON, where inside there is a String "representing" a JSON.

So, since we can do:

NSData <=> NSString

NSArray/NSDictionary <=> JSON NSData

We just have to switch between them according to the kind of data we have.

NSArray *topLevelJSON = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; 
NSString *lowLevelString = [[topLevelJSON firstObject] objectForKey:@"data"];
NSData *lowLevelData = [lowLevelString dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *final = [NSJSONSerialization JSONObjectWithData:lowLevelData options:0 error:nil];

Parse JSON response string in Objective - C

I tried to create a demo scenario with your JSON value

Here is the code :

- (void)viewDidLoad {
[super viewDidLoad];

NSString *str = @"[{\"TheatreName\": \"FunCinemas\",\"TheatreId\": 1,\"City\":\"Chandigarh\"},{\"TheatreName\":\"PVRElanteMall\",\"TheatreId\": 2,\"City\": \"Chandigarh\"},{\"TheatreName\": \"PiccadilySquare\",\"TheatreId\": 3,\"City\": \"Chandigarh\"}]";
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];

NSError *err = nil;
NSArray *jsonData = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&err];

NSMutableArray *arrResult = [NSMutableArray array];

for (NSDictionary *dict in jsonData) {

NSLog(@"TheatreName %@", dict[@"TheatreName"]);
NSLog(@"TheatreId %@", dict[@"TheatreId"]);
NSLog(@"City %@", dict[@"City"]);

[arrResult addObject:dict];
}

}


Related Topics



Leave a reply



Submit