解析这个JSON

时间:2012-12-23 14:54:32

标签: objective-c xcode json ios5

解析这个JSON时遇到了一个小问题

    {
    "@attributes": {
        "date": "23-12-2012"
    },

    "data": [

        {
        "ft_link": "google",
        "title": "CEO"

        },
        {
        "ft_link": "Yahoo",
        "title": "CEO"
        }
     ]
}

我试图获得所有'标题'项目。

NSError *jsonError = nil;
id jsonObject = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&jsonError];


NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
NSLog(@"%@", [jsonDictionary objectForKey:@"data"]);

这会记录整个JSON。但现在我想解析'标题'项目。所以我试过了:

NSLog(@"%@", [jsonDictionary objectForKey:@"data"] objectForKey:@"title"]);

但是它崩溃了,我怎么能正确地解析它呢?

崩溃:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x91583c0'

3 个答案:

答案 0 :(得分:2)

如前所述,objectForKey对NSArrays不起作用。然而,NSArrays确实实现了valueForKey,你可以用它来得到你想要的东西,`,即:

[jsonDictionary objectForKey:@"data"] valueForKey:@"title"]

这将返回包含标题的字符串数组。

objectForKey调用将返回数组,而在数组上调用valueForKey会通过在每个对象上调用valueForKey来返回对象数组。

答案 1 :(得分:1)

数据是array(词典),因此它不支持objectForKey:。它崩溃的错误可能会暗示这样。在尝试对json进行处理之前,您还应该始终检查解析json返回的任何错误。

答案 2 :(得分:0)

我不确定这是否是有效的JSON。

但是根据您的要求,您希望获得“title”的所有值。我看到有多个“标题”,因此您需要将其分解为NSArray,然后通过NSDictinary访问嵌套的objectForKey:@"title"