【问题标题】:Parsing NSDictionary data from JSONValue as a string将来自 JSONValue 的 NSDictionary 数据解析为字符串
【发布时间】:2013-05-29 07:56:08
【问题描述】:

我刚刚获取数据,但是当我尝试从 NSData 将其附加到字符串时,编译器出现异常错误。 我的代码是这样的:

NSDictionary *allDAtaDictionary = [NSJSONSerialization JSONObjectWithData:_webData options:0 error:nil];
NSString *jSonStatus = [allDAtaDictionary objectForKey:@"status"];
if([jSonStatus isEqualToString:@"OK"])
{
   NSDictionary *results = [allDAtaDictionary objectForKey:@"user_details"];
   NSLog(@"User Details :  %@",results);

在这行刚刚开始之前,一切都很好:

NSString *userID = [results objectForKey:@"userID"];

错误输出是:

* 由于未捕获的异常 'NSInvalidArgumentException' 导致应用程序终止,原因:'-[__NSCFArray objectForKey:]: 无法识别的选择器发送到实例 0x9485a00'

这是我的 jSOn 输出,NSLog(@"User Details : %@",results);

User Details :  (
        {
        userCity = California;
        userCountry = "United States";
        userDOB = "1988-03-02";
        userDetails = "";
        userEmail = "xxx@xxx.com";
        userFBID = 715296184;
        userFullName = "John Mc Grager";
        userGender = Male;
        userID = 70;
        userLastLoginTime = "2013-05-29 10:51:27";
        userLatitude = "37.7858";
        userLongtitude = "-122.406";
        userNickName = warblader;
        userPassword = "";
        userStatus = 1;
        userToken = "";
    }
)

【问题讨论】:

  • 如果每次有人问同样的问题我都能得到五分钱...好吧,线索就在上面第一行的末尾!
  • ????????????????????????????
  • 你认为__NSCFArray是什么意思?
  • @borrrden ,我希望你能仔细阅读我寻求帮助的内容......
  • 我读得很好:你没有理解你得到的对象,而是把它当作字典而不是数组(即__NSCFArray,这是整个问题的重要线索)。与下面的海报不同,我不打算在银盘上给你这么简单的答案。相反,我认为您最好了解问题所在。

标签: ios json nsurlconnection


【解决方案1】:

似乎 JSON 是一个包含一个字典的数组。你至少在这里向我们展示了什么。

所以

NSArray *results = [allDAtaDictionary objectForKey:@"user_details"];
NSLog(@"User Details :  %@",results);

assert(results.count>0);
NSDictionary *user = [results objectAtIndex:0];

NSString *userID = [results objectForKey:@"userID"];
NSLog(@"%@", userID);

【讨论】:

  • 你成就了我的一天!服务向我推送数组的 1. 元素中的数据,而不是我必须将其转换为 0.th 数组索引的字典。
【解决方案2】:

首先你需要将序列化的数据保存到一个数组中。然后你必须相应地使用它。在这种情况下

NSArray *allDAtaDictionary = [NSJSONSerialization JSONObjectWithData:_webData options:0 error:nil];

将数组记录在索引 0 中,看看你得到了什么。在此之后,您可以开始解析数据。

因此发生异常。在此处查看我的答案以解析 JSON How to parse JSON with multiple instance in Object C

【讨论】:

    【解决方案3】:

    您的响应中可能有一个数组,其中 result 字典正在保存,因此您需要使用 ObjectAtIndex 而不是调用 objectForKey

    【讨论】:

      猜你喜欢
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-27
      • 1970-01-01
      相关资源
      最近更新 更多