0

すべてのキー ペアの値を使用して JSON データを解析する方法を認識しています。以下のJSONを確認してください

{ "a": [ "a1", "a2", "a3" ], "b": [ "b1", "b2", "b3" ] }

この場合、キー値 a と b は静的キー値ではありません。これらは動的なキー値です。これを解析するにはどうすればよいですか?

4

4 に答える 4

1

それらが配列であることがわかっている場合:

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

for (NSString *key in [parsedData allKeys])
{
  // you have now a key to an array
}
于 2013-10-08T09:30:12.723 に答える
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"]];
}

このコードを試してください...

于 2013-10-08T09:43:43.607 に答える
0

私のメソッドを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);
        }];
于 2013-11-29T03:50:02.260 に答える