goo
goo

Reputation: 2280

Objective -c/JSON: How to get ObjectForKey when it's a top level object

my JSON looks like this:

[
  {
    post_number: "1",
    date: "2013-09-02",
    thumbnail: "thumbnail_address"
  },
  {
    post_number: "2",
    date: "2013-09-02",
    thumbnail: "thumbnail_address"
  },
  {
    post_number: "2",
    date: "2013-09-02",
    thumbnail: "thumbnail_address"
  },
]

I usually do something like this NSArray *blogPostsArray = [dataDictionary objectForKey:@"posts"]; but there's not a top level object called "posts". How do I get an array when there's no top level object in Objective -c?

Thank you in advance..

Upvotes: 2

Views: 260

Answers (1)

Thomas Zoechling
Thomas Zoechling

Reputation: 34263

If your top level object is an array instead of a dictionary, NSJSONSerialization will create an NSArray instance instead of a NSDictionary.
Therefore you can retrieve the contained objects via objectAtIndex: (or via [] in modern Objective-C):

NSArray* jsonArray = @[@{
                           @"post_number": @"1",
                           @"date": @"2013-09-02",
                           @"thumbnail": @"thumbnail_address"
                      },
                      @{
                           @"post_number": @"2",
                           @"date": @"2013-09-02",
                           @"thumbnail": @"thumbnail_address"
                      },
                      @{
                           @"post_number": @"2",
                           @"date": @"2013-09-02",
                           @"thumbnail": @"thumbnail_address"
                        }];
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonArray options:0 error:nil];
NSArray* deserializedArray = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
NSDictionary* first = deserializedArray[0];
NSLog(@"%@", first);

Upvotes: 1

Related Questions