0

我正在使用objective-c 解析JSON 数据。

数据如下:

{"parcels":{"12595884967":{"kj_number":"KJ6612636902","re​​cipient":"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

                }
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

我建议使用 aNSDictionary而不是NSMutableSet. 有NSDictionary一种方法allKeys可以为您提供请求的数据。

于 2013-01-25T10:29:38.843 回答