2012-08-14 55 views
0

下面是位於json.txt內容如何從這種結構中獲取數據,JSONKit

{ 
    "data": [ 
     { 
      "keyId": 3, 
      "title": "This is a fundraiser 1", 
      "budget": "1000", 
      "users": { 
       "user": [ 
        { 
         "id": "3", 
         "first_name": "A1", 
         "last_name": "A11", 
         "is_owner": "false" 
        }, 
        { 
         "id": "2", 
         "first_name": "B1", 
         "last_name": "B11", 
         "is_owner": "true" 
        } 
       ] 
      }  
     } 
    ] 
} 

我在做什麼讓idKeytitlebudget

@implementation Account 
@synthesize arr; 
-(void)parse { 
      NSString *filePath = [[NSBundle mainBundle] pathForResource:@"fundraiser_json" ofType:@"txt"]; 
      NSString *jsonString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil]; 

      NSDictionary *dict = [jsonString objectFromJSONString]; 
      self.arr    = [dict objectForKey:@"data"]; 

      for (NSDictionary *acc in self.arr) { 

       Account *account  = [[Account alloc] init]; 

       [account setKeyID: [acc objectForKey:@"keyId"]]; 
       [account setTitle: [acc objectForKey:@"title"]]; 
       [account setBudget: [acc objectForKey:@"budget"]]; 
      } 
    }  

然後我試圖訪問users,並得到它的每個user的一些信息,但我不能

有人可以幫助我如何訪問並獲取這些數據。

+1

你是否假設'users'是一個數組?它不在上面給出的JSON中,它是一個對象('NSDictionary')。 – Hejazi 2012-08-14 21:32:12

回答

3

訪問用戶數據的方式與訪問帳戶數據的方式相同。在您的JSON對象的嵌套結構中,用戶是您帳戶的一個屬性。該對象是一個字典,它有一個屬性「user」,它是一個數組。該數組的每個元素都是具有四個屬性的對象:id,first_name,last_name和is_owner。

所以當你解析你的對象時,它只是一堆嵌套的NSDictionaries和NSArrays。你可以這樣說:

... 
for (NSDictionary *acc in self.arr) { 

    NSDictionary *users = (NSDictionary*)[acc objectForKey:@"users"]; 
    NSArray *userArray = (NSArray*)[users objectForKey:@"user"]; 

    for (NSDictionary *user in userArray) { 
     NSString *id = [user objectForKey:@"id"]; 
     NSString *firstName = [user objectForKey:@"first_name"]; 
     // etc. 
    } 
} 

編輯:我寫這個答案解析您的JSON你有它在你的問題的方式,但是如果你有這種結構的控制,你會更好(這會更有意義),用戶屬性是一個直接包含用戶數據字典的數組。也許這就是你首先要做的,以及爲什麼你無法獲得數據。

+0

因爲我沒有注意到'users'也是另外一本字典,所以我無法獲得'用戶'。謝謝你的幫助.. – tranvutuan 2012-08-15 01:17:58

0

將字符串轉換爲JSON對象時,它會生成樹形結構的數據類型,其中包含可變字典和數組。 NSJSONSerialization Class Documentation總結得很好。

我想,如果要訪問例如,在列表中的第一個用戶的名字,你就需要編寫方法調用:

[[[[acc objectForKey:@"users"] objectForKey:@"user"] objectForKey:@"first_name"] objectAtIndex:0]; 

我不知道,雖然我明白你的問題或解決它。

+0

應該是'[[[acc objectForKey:@「users」] objectForKey:@「user」] objectAtIndex:0] objectForKey @「first_name」]]' – tranvutuan 2012-08-15 01:24:13

+0

對,因爲「users」是一個數組。謝謝。 – boomkin 2012-08-15 10:01:56

相關問題