I have a JSON string (from PHP\'s json_encode()
that looks like this:
[{\"id\": \"1\", \"name\":\"Aaa\"}, {\"id\": \"2\", \"name\":\"Bbb\"}]
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.