0

I have managed through tutorials to make http request and parse json object in obj-C. No from the data that I get I want to save the first 17 into an array and items from 20-33 to another. Problem is that data are not in the same order that appear to be if I do in http request but in another, so I cannot do that because they are not in the same order that should be.

Here is my code:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"connectionDidFinishLoading");
    NSLog(@"Succeeded! Received %d bytes of data",[self.responseData length]);

    // convert to JSON
    NSError *myError = nil;
    NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
    NSMutableArray *array_1 = [NSMutableArray array];
    NSMutableArray *array_2 = [NSMutableArray array];
    int index=0;

    // show all values
    for(id key in res) {
        index=index+1;
        id value = [res objectForKey:key];

        NSString *keyAsString = (NSString *)key;
        NSString *valueAsString = (NSString *)value;


       if (index<=17){
            [array_1 addObject:valueAsString];
            NSLog(@"%i: array 1 filling up: %@",index, keyAsString);
            NSLog(@"%@",array_1);

        } else if ((index>20)&&(index<=33)){
            [array_2 addObject:valueAsString];

        }
    }
}

So I want my data to be in the same order that are when I run the script in my browser. I guess it has something to do with NSDictionary but I do not know what else to use.

2 Answers 2

1

There's no easy way to achieve this. As NSDictionary's documentation states, the order of the keys in a dictionary is unspecified. If you really have to rely on the order of the items, either wrap them using an array in the JSON itself (resulting in an NSArray during parsing) or make a subclass of NSDictionary that makes the key order persist.

Sign up to request clarification or add additional context in comments.

Comments

1

An NSDictionary is just an association of keys with values. There is no order on the key/value pairs. Possible solutions:

  • Use an array instead of a dictionary as top-level object in the JSON data.
  • Choose the dictionary keys in such a way that they can be sorted.

ADDED

If the dictionary keys are sorted strings, then you could do

int index = 0;
NSArray *sortedKeys = [[res allKeys] sortedArrayUsingSelector: @selector(compare:)];
for (NSString *key in sortedKeys) {
    index = index + 1;
    NSString  *value = [res objectForKey:key];
    /* ... */
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.