IOS JSON解析

问题描述:

我知道如何解析所有的密钥对值的JSON数据。检查以下JSONIOS JSON解析

{ “一”:[ “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 
} 

//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转换为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]; 

要在字典

for (NSString *key in allKeys) 
{ 

NSArray *a = parsedDictionary[key]; 

} 

你可以用我的方法对JSON解析,

解析方法获得A和B阵列:

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