1

I am trying to convert raw json string to NSDictionary. but on NSDictionary i got different order of objects as on json string but i need exactly same order in NSDictionary as on json string. following is code i have used to convert json string

 SBJSON *objJson = [[SBJSON alloc] init];
 NSError *error = nil;
 NSDictionary *dictResults = [objJson objectWithString:jsonString error:&error];

3 Answers 3

1

From NSDictionary's class reference:

The order of the keys is not defined.

So, basically you can't do this when using a standard NSDictionary.

However, this may be a good reason for subclassing NSDictionary itself. See this question about the details.

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

Comments

0

NSDictionary is an associative array and does not preserve order of it's elements. If you know all your keys, then you can create some array, that holds all keys in correct order (you can also pass it with your JSON as an additional parameter). Example:

NSArray* ordered_keys = [NSArray arrayWithObjects: @"key1", @"key2", @"key3", .., nil];

for(NSString* key is ordered_keys) {
    NSLog(@"%@", [json_dict valueForKey: key]);
}

Comments

0
//parse out the json data
    NSError* error;


NSDictionary* json = [NSJSONSerialization 
        JSONObjectWithData:responseData //1

        options:kNilOptions 
        error:&error];

    NSArray* latestLoans = [json objectForKey:@"loans"]; //2

    NSLog(@"loans: %@", latestLoans); //3

Source: Follow this link http://www.raywenderlich.com/5492/working-with-json-in-ios-5 Good tutorial but works only on iOS5

4 Comments

but this doesn't at all answers OP's question.
NSDictionary order is not guaranteed at all. check apple documentation. You have to sort order by your self.
but this still doesn't answer the question.
then i really don't understand what question is, elaborate more.

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.