2013-10-08 146 views
0

我知道如何解析所有的密鑰對值的JSON數據。檢查以下JSONIOS JSON解析

{ 「一」:[ 「A1」, 「A2」, 「A3」 ], 「B」:[ 「B1」, 「B2」, 「 b3「 」 }

在此,鍵值a和b不是靜態鍵值。它們是動態的關鍵值。我如何解析這個?

回答

1

如果你知道他們是數組:

NSDictionary *parsedData = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error]; 

for (NSString *key in [parsedData allKeys]) 
{ 
    // you have now a key to an array 
} 
0
//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"]]; 
} 

試試這個代碼...

0

到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]; 

} 
0

你可以用我的方法對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); 
     }];