我的JSON看起来像这样:
[
{
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"
},
]
我通常做这样的事情NSArray *blogPostsArray = [dataDictionary objectForKey:@"posts"];
但是没有一个名为“帖子”的顶级对象。当Objective -c中没有顶级对象时,如何获取数组?
提前谢谢..
答案 0 :(得分:1)
如果您的顶级对象是数组而不是字典,NSJSONSerialization
将创建NSArray
实例而不是NSDictionary
。
因此,您可以通过objectAtIndex:
(或通过现代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);