Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 916
whoknows Avatar asked Dec 04 '13 12:12

whoknows


1 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];
        }
    }
}
like image 133
Janak Nirmal Avatar answered Sep 23 '22 14:09

Janak Nirmal