【问题标题】:JSON to NSDictionary. Shouldn't be this hard?JSON 到 NSDictionary。不应该这么难吗?
【发布时间】:2014-03-27 11:57:22
【问题描述】:

将 JSON 数据放入 NSDictionary 时出现错误*。我收到的错误是因为无法识别密钥。

*错误[__NSCFArray objectForKey:]: unrecognized selector sent to instance 0x8d26cd0

JSON 字符串输出如下所示:

[{"Username":"TestUsername"}]

我正在使用的代码:

if(error == nil)
{
   NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
   NSLog(@"%@",text);

   NSError *error;
   NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

   //Fails when using NSDictionary instead of NSArray
   NSLog(@"json: %@", [json objectForKey:@"Username"]);

   //NSLog(@"json: %@", json[0]);
}

当我使用 NSArray 时,这是输出:

{
    Username = Elder;
}

【问题讨论】:

  • 这里 jsonNSArray 而不是 NSDictionary。所以[json objectForKey:@"Username"] 会崩溃。所以改用[json[0] objectForKey:@"Username"],把json改成NSArray *json
  • 啊,谢谢。完美运行。

标签: ios objective-c json


【解决方案1】:

您的 JSONArray 而不是 Dictionary。在 json 数组中,第一个对象是字典。

更正了您的代码:

if(error == nil)
{
   NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
   NSLog(@"%@",text);

   NSError *error;
   NSArray *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];

   //Fails when using NSDictionary instead of NSArray
   NSLog(@"json: %@", [json[0] objectForKey:@"Username"]);

   //NSLog(@"json: %@", json[0]);
}

【讨论】:

    【解决方案2】:

    把代码改成

     NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];
    
     //Check the array count if required, if count is 0, jsonArray[0] crashes
     NSString *userName = [jsonArray[0] objectForKey:@"Username"];
    
     NSLog(@"json: %@", userName);
    

    在您的代码中 JSONObjectWithData: 返回 NSArray 而不是 NSDictionary。所以objectForKey: on NSArray 会导致崩溃。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-24
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多