我知道如何使用所有密钥对值解析 JSON 数据。检查下面的 JSON
{“a”:[“a1”,“a2”,“a3”],“b”:[“b1”,“b2”,“b3”]}
在此键值 a 和 b 不是静态键值。它们是动态键值。我如何解析这个?
如果你知道它们是数组:
NSDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
for (NSString *key in [parsedData allKeys])
{
// you have now a key to an array
}
要将 JSON 转换为 NSDictionary:
NSError *error= nil;
NSDictionary *parsedDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];
parsedDictionary 将是
parsedDictionary = {
a = [a1,a2,a3],
b = [b1,b2,b3]
};
获取字典中的所有键
NSArray *allKeys = [parsedDictionary allKeys];
获取字典中的 a 和 b 数组
for (NSString *key in allKeys)
{
NSArray *a = parsedDictionary[key];
}
//Get json data in Dictionary
json = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &error];
NSLog(@"%@",json);
NSArray * responseArr = json[@"Deviceinfo"]; // Here you need pass your key
for(NSDictionary * dict in responseArr)
{
[delegate.firstArray addObject:[dict valueForKey:@"a"]];
}
试试这个代码...
你可以使用我的方法进行json解析,
解析方法:
-(void)jsonDeserialize:(NSString *)key fromDict:(id)content completionHandler:(void (^) (id parsedData, NSDictionary *fromDict))completionHandler{
if (key==nil && content ==nil) {
completionHandler(nil,nil);
}
if ([content isKindOfClass:[NSArray class]]) {
for (NSDictionary *obj in content) {
[self jsonDeserialize:key fromDict:obj completionHandler:completionHandler];
}
}
if ([content isKindOfClass:[NSDictionary class]]) {
id result = [content objectForKey:key];
if ([result isKindOfClass:[NSNull class]] || result == nil) {
NSDictionary *temp = (NSDictionary *)content;
NSArray *keys = [temp allKeys];
for (NSString *ikey in keys) {
[self jsonDeserialize:key fromDict:[content objectForKey:ikey] completionHandler:completionHandler];
}
}else{
completionHandler(result,content);
}
}
}
方法调用:
NSData *content = [NSData dataWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"Sample" ofType:@"json"]];
NSError *error;
//获取序列化的json数据...
id dictionary = [NSJSONSerialization JSONObjectWithData:content options:NSJSONReadingMutableContainers error:&error];
//获取名为GetInfo的键的数据
[self jsonDeserialize:@"GetInfo" fromDict:dictionary completionHandler:^(id parsedData, NSDictionary *fromDict) {
NSLog(@"%@ - %@",parsedData,fromDict);
}];