When converted to Cocoa Foundation objects, JSON splits into a bunch of nested NSArrays
and NSDictionary
, eventually leading to NSString
s, NSNumber
and NSNull
s. Ideally, you will work forward from the web service documentation, but you can work backwards from the description that the root object prints through NSLog
.
From your log, I see that expanded_url
is a member of an unnamed object, which is the first entry in the media
array, which is a member of the entities
object. An unnamed object containing entities
is part of the array, which will return the JSON deserializer. Therefore, you want to do something like (if written out in a long form for presentation and without any verification):
NSArray *result = [NSJSONSerialization ... NSDictionary *firstObject = [result objectAtIndex:0]; NSDictionary *entities = [firstObject objectForKey:@"entities"]; NSArray *media = [entities objectForKey:@"media"]; NSDictionary *relevantObject = [media objectAtIndex:0]; NSString *expandedUrl = [relevantObject objectForKey:@"expanded_url"];
The main risk is that the web service may return an empty array for media
, causing objectAtIndex:0
throw an exception or return something other than the array as the root object or in some other way to adjust the type somewhere along the line . Objective-C's usual nil
messaging rules should save you most of the problems with dictionaries. It is enough how validation for the application is to call the court.
Tommy source share