0

我来自 URL 的 json 响应是:

[
 {"status":0,
  "id":"26",
   "content":"See info field for info",
   "time":1347565292761,
    "info": {"id":"26",
    "name":"Ruti",
    "twitterPageFollowers":null,
     "facebookPageLikes":null,
     "activeEmailClients":1}
  }
 ]

我需要从中提取以下字符串:

twitterPageFollowers
facebookPageLikes
activeEmailClients

我该怎么做?

我尝试像这样解析

NSData *urlData=[NSURLConnection sendSynchronousRequest:serviceRequest returningResponse:nil error:nil ];
    NSString *returnString=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
    NSData *jsonData = [returnString dataUsingEncoding:NSUTF8StringEncoding];
    NSArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
    NSDictionary *response = [json objectAtIndex:0];
    NSString *info = [response objectForKey:@"info"];
    NSData *businessInfoString = [info dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *businessInfo =
    [NSJSONSerialization JSONObjectWithData: businessInfoString
                                    options: NSJSONReadingMutableContainers
                                      error: nil];

并且返回数据没问题,但我得到 [__NSCFDictionary dataUsingEncoding:unrecognized selector sent to instance for last NSDictionary creation from info field。有什么问题或检索上述字段的更短方法是什么?

4

1 回答 1

1

当您使用 检索“信息”字段[response objectForKey:@"info"];时,您已经得到一个NSDictionary!(而不是NSString

这就是为什么当您尝试调用dataUsingEncoding:此对象(您认为是 an NSStringbut is as NSDictionary)时,您会得到异常。

无需检索"info"key 的值,然后将其NSData转换为 JSONObject 并将其转换回 JSONObject,因为它已经是 JSONObject,即NSDictionary在您的情况下。为什么还要费心尝试来回转换它,而[response objectForKey:@"info"];已经businessInfo在代码末尾返回了您期望的字典?

于 2012-09-13T20:16:42.733 回答