我有以下json
{"status":1,"value":{"details":{"40404000024769":[{"name":"","email":""}]}}}
我解析它如下,
NSString *statusCode = [NSString stringWithFormat:@"%@",jsonDic[@"status"]];
NSDictionary *valueDict = [jsonDic objectForKey:@"value"];
NSArray *details = [valueDict objectForKey:@"details"];
NSLog(@"%@",details);
for (NSDictionary *response in details){
NSLog(@"adsf %@",response);
}
}
以下是我的错误日志
这可以获得唯一的40404000024769
,但不能获得40404000024769
的值。
我尝试使用[response valueForKey:@"name"]
并且应用崩溃了。
我怎样才能获得姓名,电子邮件的价值?
2016-04-27 16:24:02.967 Vaighai Export[311:10625] ***Terminating app due to uncaught exception 'NSUnknownKeyException', reason:'[<__NSCFString 0x14e56870> valueForUndefinedKey:]:this class is not key value coding-compliant for the key name.'
答案 0 :(得分:3)
您的JSON结构是:
-NSDictionary
--Number
--NSDictionary
---NSDictionary
----NSDictionary
-----NSArray
------NSDictionary
键details
有一个字典作为值,而不是你假设的数组。将您的代码更改为:
注意:这只是向您展示如何解析错误的示例。您需要在应用程序中处理真实世界json的案例。
NSString *statusCode = [NSString stringWithFormat:@"%i",jsonDic[@"status"]]; //We got status
NSDictionary *valueDict = [jsonDic objectForKey:@"value"]; //We got value dic
NSDictionary *detailDic = [valueDict objectForKey:@"details"]; //We got details dic
NSArray * internalArr = [detailDic objectForKey:@"40404000024769"]; //We got array of dictionaries
//Iterate over this array to log internal dictionaries
for(NSDictionary *nameDic in internalArr)
{
NSLog(@"Name: %@ email: %@",[nameDic objectForKey:@"name"],[nameDic objectForKey:@"email"]);
}
答案 1 :(得分:1)
首先从详细信息字典中获取allkeys,然后将这些键放入数组中,然后在该数组的零索引处,该键可用,找到该键内的数组。
答案 2 :(得分:1)
使用此代码
NSDictionary *valueDict = [jsonDic objectForKey:@"value"];
NSDictionary *details = [valueDict objectForKey:@"details"];
NSArray *YourArray= [details objectForKey:@"40404000024769"];
NSString *Name = [YourArray objectAtIndex:0]valueForKey:@"name"];
NSString *Email = [YourArray objectAtIndex:0]valueForKey:@"email"];
答案 3 :(得分:1)
status
是一个整数
NSInteger statusCode = [jsonDic[@"status"] integerValue];
value
包含字典details
NSDictionary *valueDict = [jsonDic objectForKey:@"value"];
NSDictionary *details = [valueDict objectForKey:@"details"];
details
包含字典中的数组。在数组的第0项中,有一个包含所请求的name
和email
键的字典。
for (NSString *key in details){
NSLog(@"key %@",key);
NSDictionary *data = details[key][0];
NSLog(@"name %@ - email %@", data[@"name"], data[@"email"]);
}
答案 4 :(得分:1)
key 40404000024769
是一个不是数组的字典。
只需添加一行即可获取NSDictionary *valueDict = [jsonDic objectForKey:@"value"];
NSDictionary *details = [valueDict objectForKey:@"details"];
NSArray *ar = [details objectForKey:@"40404000024769"];
for (NSDictionary *response in ar){
NSLog(@"name: %@ email: %@",[response objectForKey:@"name"],[response objectForKey:@"email"]);
}
键值。
将代码更改为:
date