当我将 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;
}
最佳答案
您的 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]);
}
关于ios - JSON 到 NSDictionary。不应该这么难吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22686899/