我正在使用objective-c 解析JSON 数据。
数据如下:
{"parcels":{"12595884967":{"kj_number":"KJ6612636902","recipient":"Krzysztof Racki","courier":"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
}