我使用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
}
你好。你已經指示了我正確的方式,謝謝:) 問題是我解析JSON使用以下行:
NSJSONSerialization* jsonObject = [ NSJSONSerialization JSONObjectWithData:nsData options:NSJSONReadingAllowFragments error:nil ];
– lrav,並且我不允許「包裹」作爲字典,因爲沒有選擇器等等等等等等。顯然,將其更改爲NSDictionary *解決了這個問題,但我真的不知道它爲什麼會起作用(我嘗試將新的NSDictionary *值初始化爲= jsonObject(類型NSJSONSerialization),但它們不是assigment-compaitible,所以我不確定是否NSJSONSerialization是NSDictionary的子類,或者爲什麼它可以工作。無論如何它的工作非常感謝你:) – lrav