2013-05-20 158 views
0

如何获取此JSON。它具有动态值。下面是json。如何获取此JSON

{ 
Level1: 
    { 
    row1: 
    { 
    1: "on", 
    2: "on", 
    3: "on", 
    4: "on", 
    5: "on", 
    6: "on", 
    7: "on", 
    8: "on", 
    9: "on", 
    10: "on", 
    attr: { 
    total: "10", 
    type: "gold" 
    } 
    }, 
    row2: { 
    1: "on", 
    2: "on", 
    3: "on", 
    4: "on", 
    5: "on", 
    6: "on", 
    7: "on", 
    8: "on", 
    9: "on", 
    10: "on", 
    attr: { 
    total: "10", 
    type: "gold" 
    } 
    } 
    }, 
    Level3: { 
row1: { 
1: "on", 
2: "on", 
3: "on", 
4: "on", 
5: "on", 
6: "on", 
7: "on", 
8: "on", 
    9: "on", 
10: "on", 
attr: { 
total: "10", 
type: "silver" 
} 
} 
} 
} 

在这个数量的层次上,行数是动态的,里面的座位也是动态的,如何解决这个问题我没有得到它。请为上述指导,我已经花了一天的时间。下面是我的代码,我曾尝试过。

arrLevels = [self.mGetDataDict allKeys];   // getting all levels here in array 
    NSLog(@"keys:%@", arrLevels); 

    for(int i=0; i<[arrLevels count]; i++)  // trying to get rows in array 
{ 
    receiveDataDict = [self.mGetDataDict valueForKey:[arrLevels objectAtIndex:i]]; 
    [arrRows addObject:[NSString stringWithFormat:@"%d", [receiveDataDict count]]]; 
    NSLog(@"data:%@", receiveDataDict); 
    for(int j=0; j<[receiveDataDict count]; j++) 
    { 
     NSLog(@"count:%d", [receiveDataDict count]); 
     dictRow = [receiveDataDict valueForKey:@"attr"]; 
     [arrTot addObject:[dictRow valueForKey:@"total"]]; 
     [arrType addObject:[dictRow valueForKey:@"type"]]; 
    } 
} 

回答

2

第1步:从here下载JSON框架IOS和

步骤2库文件将它添加到您的项目:进口#import "JSON.h".h文件

第3步:从服务器获取您的JSON数据或本地。

NSData *data = ...Your JSON Data...; 
NSString *responseString = [[NSString alloc] initWithBytes:[data bytes] length:[data length] encoding:NSUTF8StringEncoding]; 

// Parse it Using SBJSON 
NSDictionary *dictResults = [NSDictionary dictionaryWithDictionary:[responseString JSONValue]]; 

// Read all Levels 
for(NSString *key in [dictResults allKeys]) 
{ 
    NSLog(@"Accessing .... %@",key); 
    for(NSString *rowKey in dictResults[key]) 
    { 
     NSLog(@"%@",rowKey); 
     for(NSString *valueKey in dictResults[key][rowKey]) 
     { 
      NSLog(@"%@ -> %@",valueKey,dictResults[key][rowKey][valueKey]); 
     } 
     NSLog(@"--------ROW OVER------------\n");    
    } 
    NSLog(@"--------------------\n"); 
} 
+0

我想问为什么它从底部取数据意味着它首先显示level3最后一行,然后是level2以及更远。 –

+0

这里的数据排序不会保留,它会以随机访问的方式访问数据,而不是顺序的方式,这就是为什么。 –

+0

我们可以处理它,有没有办法呢。 –

4

Why are you not using the NSJSONSerialization class?我已经为你连接了Apple文档,现在你知道这个非常有用的类的名字,你应该能够很容易地找到大量可以使用的教程。

只需将您的数据提供给该数据,您将返回一个NSDictionary对象。

当然,下一个挑战将是如何处理新解析字典下出现的各种Objective-C对象。

执行此操作的一种方法是通过keyPaths。例如:

NSString * onOrOff = [receiveDataDict valueForKeyPath: @"row1.1"]; 

Here is a related question with some answers that may help you out