How to use NSJSONSerialization How to use NSJSONSerialization ios ios

How to use NSJSONSerialization


Your root json object is not a dictionary but an array:

[{"id": "1", "name":"Aaa"}, {"id": "2", "name":"Bbb"}]

This might give you a clear picture of how to handle it:

NSError *e = nil;NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData: data options: NSJSONReadingMutableContainers error: &e];if (!jsonArray) {  NSLog(@"Error parsing JSON: %@", e);} else {   for(NSDictionary *item in jsonArray) {      NSLog(@"Item: %@", item);   }}


This is my code for checking if the received json is an array or dictionary:

NSError *jsonError = nil;id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];if ([jsonObject isKindOfClass:[NSArray class]]) {    NSLog(@"its an array!");    NSArray *jsonArray = (NSArray *)jsonObject;    NSLog(@"jsonArray - %@",jsonArray);}else {    NSLog(@"its probably a dictionary");    NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;    NSLog(@"jsonDictionary - %@",jsonDictionary);}

I have tried this for options:kNilOptions and NSJSONReadingMutableContainers and works correctly for both.

Obviously, the actual code cannot be this way where I create the NSArray or NSDictionary pointer within the if-else block.


It works for me. Your data object is probably nil and, as rckoenes noted, the root object should be a (mutable) array. See this code:

NSString *jsonString = @"[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]";NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];NSError *e = nil;NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];NSLog(@"%@", json);

(I had to escape the quotes in the JSON string with backslashes.)