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

Viewed 25945

I come from Android dev, so sorry if I'm missing obvious iOS concepts here.

I have a JSON feed that looks like:

{"directory":[{"id":0,"fName":"...","lName":"...","title":"...","dept":"...","bld":"...","room":"...","email":"...","phone":"..."},{"id":1,"fName":"...","lName":"...","title":"...","dept":"...","bld":"...","room":"...","email":"...","phone":"..."}]}

Then, I have a Staff.h and .m with a class with properties to match it (id, fName, lName) ect.

I've been working at this for hours, but I can't seem to parse the JSON string to an array of Staff objects. The end goal is to get them into Core Data, so any advice would be nice.

Tutorials I've read haven't shown how to work with a JSON string in the form of {"directory":[{...}]} I had no problem doing this in my Android app, but I'm out of ideas here for iOS (6) in objective-c.

Thanks for reading.

7 Answers

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];
        }
    }
}

Use: NSJSONSerialization

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

An object that may be converted to JSON must have the following properties:

The top level object is an NSArray or NSDictionary.
All objects are instances of NSString, NSNumber, NSArray, NSDictionary, or NSNull.
All dictionary keys are instances of NSString.
Numbers are not NaN or infinity.

You will get NSDictionary then you can parse (create) it to your object and then use it in CoreData.

Use following code:

NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];

This will covert json data onto NSDictionary, which is similar to hashmap on android. I think this will help you. :)

you can use NSJSonSerialisation or AFNetworking library. Here is the example of AFNetworking to parse json response

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager GET:@"http://example.com/resources.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
    NSDictionary *json = (NSDictionary *)responseObject;
    NSArray *staffArray = json[@"directory"];

[staffArray enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop){
      Staff *staff = [[Staff alloc] init];
    staff.id = [[obj objectForKey:@"id"] integerValue];
    staff.fname = [obj objectForKey:@"fName"];
    staff.lname = [obj objectForKey:@"lName"]; 

   //add data to new array to store details
   [detailsArray addObect:staff);
} ];

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}]; 

then use Core Data framework to store data.

I would take a look at RestKit. It provides object-mapping and CoreData backed storage.

For this, you can SBJSON framework.

You have to convert the response string into an NSDictionary like

 NSString *responseString = [[NSString alloc]initWithData:responseData encoding:NSUTF8StringEncoding];
    NSDictionary *dic = [responseString JSONValue];

Now you can create an object for Staff class.

Staff *staff = [[Staff alloc]init];

Then you can store values in this object like

staff.firstname = [[[dic objectForKey:@"directory"] objectAtIndex:0] objectForKey:@"fName"];

Now you can pass this single object to other classes

You can use the handmade solution proposed by @janak-nirmal, or use a library like jastor, https://github.com/elado/jastor, it doesn't make much difference. I warn you against Restkit, because the ratio benefits-vs-pain is very low, in my opinion. Moreover, it could be as use a tank to kill a fly in your scenario.

Related