0

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

                }
4

2 に答える 2

3

A set doesn't store keys. You want to get a dictionary from the 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
}

Getting the keys in an array first is optional, you could iterate over the parcels dictionary directly: for (NSString *key in parcels) {.

于 2013-01-25T10:16:45.663 に答える
0

NSDictionaryの代わりにa を使用することを提案しますNSMutableSet。には、要求されたデータを提供するNSDictionaryメソッドがあります。allKeys

于 2013-01-25T10:29:38.843 に答える