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];
shrestha2lt8
  • 305
  • 1
  • 9

3 Answers3

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.

Community
  • 1
  • 1
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

prashant
  • 1,920
  • 14
  • 26
user431791
  • 341
  • 2
  • 17
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]);
}
Max
  • 16,679
  • 4
  • 44
  • 57