Swissdude Swissdude - 3 months ago 23x
Objective-C Question

iOS - Convert a JSON object to an ordered array

I have a JSON file with key/value-pairs for a list of countries and their country-codes. I'm reading it with Objective-C and want to present it in a

Problem is, when I store the JSON data into a
, the original order is lost and the order of the
elements is pretty arbitrary (I know, dictionaries don't have a particular order).

What's the easiest way to preserve to original order? Do I have to create two files, one with the country-codes and one with the country names in the same order and read both into an array? - I really wanna avoid that...


As per request, an excerpt of the JSON-Data (stored in a local file)

"as":"American Samoa",
"ag":"Antigua and Barbuda",
"ac":"Ascension Island (Atlantic ocean)",
"bv":"Bouvet Island (Atlantic ocean)",
... }

[Edit 2]

I'm using this code to read the JSON data and convert it to a

NSURL *jsonPath = [[NSBundle mainBundle] URLForResource:@"countries" withExtension:@"json"];
NSString *stringPath = [jsonPath absoluteString];

NSData *countriesJSON = [NSData dataWithContentsOfURL:[NSURL URLWithString:stringPath]];

NSDictionary *parsedJson = [NSJSONSerialization JSONObjectWithData:countriesJSON options:0 error:nil];


You can change your JSON data to

{"as":"American Samoa"},

Then use the code like:

NSURL *jsonPath = [[NSBundle mainBundle] URLForResource:@"sample" withExtension:@"json"];
NSData *countriesJSON = [NSData dataWithContentsOfURL:jsonPath];
NSMutableArray *countryArray = [NSJSONSerialization JSONObjectWithData: countriesJSON options:NSJSONReadingMutableContainers error:nil];

The JSON is converted to a ordered array called countryArray. the elements of the countryArray is a NSDictionary instance.