2013-01-25 18 views
0

我使用objective-c解析JSON數據。NSJSONSerialization - 數組中的鍵名稱

的數據如下:

{ 「包裹」:{ 「12595884967」:{ 「kj_number」: 「KJ6612636902」, 「接受者」: 「的Krzysztof Racki」, 「信使」: 「3」} }}

我有一個對象「包裹」,它有包的鍵。現在雖然我沒有使用JSONSerialization類解壓縮這個問題,但我不知道如何獲取一個密鑰名稱(我的意思是,如何從代碼讀取值12595884967)。

代碼:

if ([ NSJSONSerialization isValidJSONObject:jsonObject ]) { 

    // we are getting root element, the "parcels" 
    NSMutableSet* parcels = [ jsonObject mutableSetValueForKey:@"parcels" ]; 

    // get array of NSDictionary*'ies 
    // in this example array has single NSDictionary* element with flds like "kj_number" 
    NSArray* array = [ parcels allObjects ]; 

    for (int i = 0 ; i < [ array count ] ; ++i) { 

     NSObject* obj = [ array objectAtIndex: i ]; 

     // the problem: how i get this dictionary KEY? string value of 12595884967 
     // how I should get it from code here? 
     // like: number = [ obj name ] or maybe [ obj keyName ] 

     if ([ obj isKindOfClass:[ NSDictionary class ] ]) { 
      // this always evaluates to true 
      // here we do reading attributes like kj_number, recipient etc 
      // and this works 
     } 

    } 
    } 

例如在java中它是:

   JSONObject json = response.asJSONObject(); 
     JSONObject parcels = json.getJSONObject("parcels"); 

     @SuppressWarnings("unchecked") 
     Iterator<String> it = parcels.keys(); 

     while (it.hasNext()) {      

      String key = it.next(); // value of 12595884967 
        Object value = parcel.getObject(key); // JSONObject ref with data 

       } 

回答

3

一集不存儲密鑰。你想從JSON獲得一本字典。

NSDictionary* parcels = [jsonObject objectForKey:@"parcels"]; 

// get the keys 
NSArray *keys = [parcels allKeys]; 
for (NSString *key in keys) { 
    NSDictionary *parcel = [parcels objectForKey:key]; 
    // do something with parcel 
} 

獲取鍵陣列中的第一個是可選的,你可以遍歷包裹直接詞典:for (NSString *key in parcels) {

+0

你好。你已經指示了我正確的方式,謝謝:) 問題是我解析JSON使用以下行:NSJSONSerialization* jsonObject = [ NSJSONSerialization JSONObjectWithData:nsData options:NSJSONReadingAllowFragments error:nil ]; lrav

+0

,並且我不允許「包裹」作爲字典,因爲沒有選擇器等等等等等等。顯然,將其更改爲NSDictionary *解決了這個問題,但我真的不知道它爲什麼會起作用(我嘗試將新的NSDictionary *值初始化爲= jsonObject(類型NSJSONSerialization),但它們不是assigment-compaitible,所以我不確定是否NSJSONSerialization是NSDictionary的子類,或者爲什麼它可以工作。無論如何它的工作非常感謝你:) – lrav

0

我會建議使用NSDictionary而不是NSMutableSetNSDictionary有一個方法allKeys,它會爲您提供所需的數據。

+0

哦,我爲時已晚。已經給出的答案... – neo74

+0

無論如何,謝謝你。我只是沒有知道「[NSJSONSerialization JSONObjectWithData:NSData選項:NSJSONReadingAllowFragments錯誤:無]的結果;」可以被鑄造到NSDictionary *和工作 – lrav