无法解析基本的JSON - iOS

时间:2013-11-06 15:44:52

标签: ios json cocoa-touch parsing facebook-graph-api

我有一个iOS应用程序,可以从Facebook API下载并解析JSON文件。

然而,每当我尝试解析它时,我的应用程序崩溃,我收到此错误:

2013-11-06 15:31:41.473 JSONTESTER[10881:70b] -[__NSCFDictionary objectAtIndex:]: unrecognized 
selector sent to instance 0x10d01bd30
2013-11-06 15:31:41.476 JSONTESTER[10881:70b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x10d01bd30'

以下是我要解析的简单JSON文件:

{


"id": "xxxxxxxxxx",
   "name": "Dan Sadjadian",
   "home": {
      "data": [
         {
            "id": "xxxxxxxxxxxxxxxxxxxxxx",
            "from": {
               "name": "Jane Smith",
               "id": "xxxxxxxxxxxxxxx"
            },
            "message": "deadline is only 16 days!!! Where are you guys!!!!!!!!! Please shall we start!!!!!",
            "actions": [
               {
                  "name": "Comment",
                  "link": "https://www.facebook.com/xxxxxxx/posts/xxxxxxxxxxx"
               },
               {
                  "name": "Like",
                  "link": "https://www.facebook.com/xxxxxxxxx/posts/xxxxxxxxxxxx"
               }
            ],
            "privacy": {
               "value": ""
            },
            "type": "status",
            "status_type": "mobile_status_update",
            "created_time": "2013-11-06T14:40:23+0000",
            "updated_time": "2013-11-06T14:40:23+0000"
         },
       ],
     },
}

这是我应该工作的代码......

cell.username.text = [[[[[facebook_array objectAtIndex:index] valueForKey:@"data"] objectAtIndex:0] valueForKey:@"from"] valueForKey:@"name"];

正如您所看到的,我正在尝试访问位于“home”中“data”数组中“from”的“name”。

我做错了什么?

谢谢,Dan。

3 个答案:

答案 0 :(得分:2)

应该是

NSArray *arrData=[MAIN_DICTIONARY objectForKey:@"data"];

NSDictionary *data=[arrData objectForIndex:0];

NSDictionary *from=[data objectForKey:@"from"];

NSLog(@"Name = %@", [from objectForKey:@"name"]);

我希望它可以帮助您了解它是如何工作的。

答案 1 :(得分:1)

我认为第一步是选择home对象而不是[index]

给出你的json文件。

你正在做[index].data.[0].from.name

您的数据看起来像home.data.[0].from.name

在linux / gnustep上,这就是我获取home.data.[0].from.name属性的方法,我将您的示例保存为fb.json,如上所述:

NSError * error;

NSData * jsdata = [NSData dataWithContentsOfFile:@"fb.json"];
id jsDict = [NSJSONSerialization JSONObjectWithData:jsdata
                                            options:0
                                              error:&error];
// not: data.from.name
// but: home.data.from.name
NSDictionary * home = [jsDict objectForKey:@"home"];
NSArray * data = [home objectForKey:@"data"];
NSDictionary * firstObj = [data objectAtIndex:0];
NSDictionary * from = [firstObj objectForKey:@"from"];
NSString * name = [from objectForKey:@"name"];

NSLog( @"%@", name);

输出:

 Jane Smith

如果示例中的整个json对象都在fb的实际数据中的数组中,那么您将从[index]开始,但下一步需要选择home

答案 2 :(得分:0)

很明显NSDictionary / NSMutableDictionary类没有objectAtIndex方法。它来自NSArray。我猜你只能使用objectForKey来浏览JSON。