How to use JSONKit to deserialize a json string into dictionary? I couldn't find any examples.
1 Answer
Use the NSString interface that comes with JSONKit. For example:
NSDictionary *deserializedData = [jsonString objectFromJSONString];
You'll either need to know in advance what sort of container you're going to get from the JSON data, or else test the object you get back to figure out its type. (You can use -isKindOfClass: for this.) Most of the time, you already have an expectation of what's in the JSON data, so you know to expect a dictionary or an array, but it's still a good idea to check the class of the object you get back.
6 Comments
happy_iphone_developer
Thanks for your reply. I get back a json of structure like { ResultCount =7; ResultLimit=30; ResultList=({ AlbumId=111;ArtistId=203},{AlbumId=112;ArtistId=203}); Status=0}. The ResultList is an array. How can I get the AlbumId and ArtistId in an Array?
Caleb
It looks like you've got a dictionary, so the line I showed you above should work in this case. The key you want is "ResultList", so you'd say
NSArray *resultList = [deserializedData objectForKey:@"ResultList"]; to get the associated array of dictionaries. Each object in resultList will be a dictionary with keys "AlbumID" and "ArtistID", which I think is what you want. If you instead want separate arrays of those two values, use NSArray *albums = [resultList valueForKey:@"AlbumID"];. Same for ArtistID.happy_iphone_developer
I am just hitting one road block after another. When I try to loop through the array the application exits. for (int i=0; i<[resultArray count]; i++) { NSLog(@"Value%@:",i); }
Caleb
Why does the application exit? Look in the console for an error message. Also, run the app in the debugger and turn on the 'Stop on Objective-C Exceptions' option. Read the error message, figure out where the problem is occurring, place some breakpoints, look at your variables just before the app exits. You can do this.
happy_iphone_developer
Dont know why the application was exiting. When i tried to set the dataSource of tableView to that array, the application kept crashing. Anyway found a way around it by iterating it through the dictionary and adding each value to an array.
|