NSJSONSerialization - 数组中的键名

时间:2013-01-25 10:11:14

标签: iphone cocoa-touch

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

数据如下:

{“parcels”:{“12595884967”:{“kj_number”:“KJ6612636902”,“收件人”:“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

                }

2 个答案:

答案 0 :(得分:3)

套装不存储钥匙。你想从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
}

首先获取数组中的键是可选的,您可以直接遍历parcels字典:for (NSString *key in parcels) {

答案 1 :(得分:0)

我建议使用NSDictionary代替NSMutableSetNSDictionary有一个方法allKeys,可以为您提供所请求的数据。