2013-05-20 204 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