Swissdude Swissdude - 4 months ago 47
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

UIPicker
.
Problem is, when I store the JSON data into a
NSDictionary
, the original order is lost and the order of the
UIPicker
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...

[Edit]

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

{"af":"Afghanistan",
"al":"Albania",
"dz":"Algeria",
"as":"American Samoa",
"ad":"Andorra",
"ao":"Angola",
"ai":"Anguilla",
"aq":"Antarctica",
"ag":"Antigua and Barbuda",
"ar":"Argentina",
"am":"Armenia",
"aw":"Aruba",
"ac":"Ascension Island (Atlantic ocean)",
"au":"Australia",
"at":"Austria",
"az":"Azerbaijan",
"bs":"Bahamas",
"bh":"Bahrain",
"bd":"Bangladesh",
"bb":"Barbados",
"by":"Belarus",
"be":"Belgium",
"bz":"Belize",
"bj":"Benin",
"bm":"Bermuda",
"bt":"Bhutan",
"bo":"Bolivia",
"ba":"Bosnia",
"bw":"Botswana",
"bv":"Bouvet Island (Atlantic ocean)",
"br":"Brazil",
... }


[Edit 2]

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

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];

Answer

You can change your JSON data to

[
{"af":"Afghanistan"},
{"al":"Albania"},
{"dz":"Algeria"},
{"as":"American Samoa"},
{"ad":"Andorra"},
{"ao":"Angola"},
{"ai":"Anguilla"},
...
]

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.