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

标签 ios objective-c json

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

*错误[__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]);
}

关于ios - JSON 到 NSDictionary。不应该这么难吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22686899/

相关文章:

iphone - iOS:只绘制 UImage 的一部分

json - OpenShift V3 : understanding the process with Docker

ios - 扩展 View 时 SwiftUI 预览崩溃

iphone - 使用自定义 segue 时 UIActivityIndi​​catorView 卡住

ios - 访问字典数组的嵌套数组

python - 如何从python中的文件中读取多个词典?

c# - JSON 文件和 LINQ 求和与分组

ios - keyboardWillShow 被其他应用程序的键盘调用

iphone - A/同步 NSURLConnection : get response without download data?

ios - 使用 Screen Edge Pan Gesture Recognizer 在 WebView 中后退和前进