1

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..

4

1 回答 1

1

如果您的顶级对象是数组而不是字典,NSJSONSerialization则将创建一个NSArray实例而不是NSDictionary. 因此,您可以通过(或现代 Objective-C 中的 via)
检索包含的对象:objectAtIndex:[]

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);
于 2013-09-05T05:44:28.183 回答