Objective-cを使用してJSONデータを解析しています。
データは次のとおりです。
{"parcels":{"12595884967":{"kj_number": "KJ6612636902"、 "recipient": "Krzysztof Racki"、 "courier": "3"}}}
パッケージのキーを持つオブジェクト「parcels」があります。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
}