使用NSJSONSerialization解析json结果

时间:2013-07-29 18:14:03

标签: ios objective-c json

我正在尝试解析这个json:

{
    "myData": [
        {
            "date": "2013-07-29",
            "preferredMeetingLocation": "home",
            "isbn": null,
            "category": "Clothing",
            "price": "5",
            "title": "clothingstuff",
            "description": "Desc"
        },
        {
            "date": "2013-07-29",
            "preferredMeetingLocation": "home2",
            "isbn": null,
            "category": "Clothing",
            "price": "2",
            "title": "other",
            "description": "Desc2"
        }
    ]
}

到目前为止,我有:

    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
    NSDictionary *results = [json objectForKey:@"myData"];
for (NSDictionary *item in results) {
    NSLog(@"results::%@", [results objectForKey:@"title"]);
}

但我得到Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8877e40'

主要目标是能够解析收到的数据,然后在单元格中显示每组信息。

我做错了什么?

2 个答案:

答案 0 :(得分:2)

该行

 NSLog(@"results::%@", [results objectForKey:@"title"]);
 //                        ^---- Wrong variable used here!

应该是

 NSLog(@"results::%@", [item objectForKey:@"title"]);

答案 1 :(得分:1)

results应该是一个数组。而且你正在记录错误的对象。

NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil];
NSArray *results = [json objectForKey:@"myData"];
for (NSDictionary *item in results) {
    NSLog(@"title::%@", [item objectForKey:@"title"]);
}