質問

I have the following code to download a JSON file from my server:

- (void) queryAPI:(NSString*)query withCompletion:(void (^) (id json))block{
    NSURL *URL = [NSURL URLWithString:@"http://myAPI.example/myAPIJSONdata"];
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    AFHTTPRequestOperation *op = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    op.responseSerializer = [AFJSONResponseSerializer serializer];
    [op setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
        block(responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
        block(nil);
    }];
    [[NSOperationQueue mainQueue] addOperation:op];
}

and the JSON file is like the following example:

{
    "dict":{
        "first key": [val1, val2, val3],
        "second key": [val1, val2, val3],
        "third key": [val1, val2, val3],
        "fourth key": [val1, val2, val3]
     }
}

I need to keep the keys at the same order they come on JSON file, but when I enumerate the returned NSDictionary with [dict allKeys], I get the keys disordered, like this:

fourth key    
second key    
first key    
third key

I also tried to use [dict keyEnumerator] but the result is exactly the same.

Is there any way to keep the keys at the same order they are on JSON file?

役に立ちましたか?

解決

NSDictionary in Cocoa does not keep order of elements. So using AFJSONResponseSerializer it is impossible to keep the keys in the same order they are in JSON file. You have to parse JSON yourself or change JSON structure to use NSArray.

For example:

{
    [
        {"name" : "first key", "value" : [val1, val2, val3]},
        {"name" : "second key", "value" : [val1, val2, val3]},
        {"name" : "third key", "value" : [val1, val2, val3]},
        {"name" : "fourth key", "value" : [val1, val2, val3]}
     ]
}

UPDATE:

This thread could be useful for you Keeping the order of NSDictionary keys when converted to NSData with [NSJSONSerialization dataWithJSONObject:]

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top