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



当我将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;
}

您的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]);
}

将代码改为

 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造成崩溃

相关内容

最新更新