JSON到NSDictionary。难道不应该这么难吗?

时间:2014-03-27 11:57:22

标签: ios objective-c json

当我将JSON数据放入NSDictionary时,我收到错误*。我收到的错误是因为密钥未被识别。

*错误[__ NSCFArray objectForKey:]:无法识别的选择器发送到实例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;
}

2 个答案:

答案 0 :(得分:2)

JSON Array不是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]);
}

答案 1 :(得分:0)

将代码更改为

 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: NSArray导致崩溃。