Reputation: 2280
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
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