Common task, converting strings to a JSON format. Yes, easy, plenty of answers on StackOverflow about this.
What is not as easy is to understand for me is why the order I get is different from the order I put the pair objects in the NSDictionary.
That's the code I wrote:
-(NSString*)createJSONstring
{
//http://www.raywenderlich.com/5492/working-with-json-in-ios-5
NSDictionary* dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
@"<xx3-xxxx>",@"from",
@"<xxx-xxx>",@"to",
@"<Bla bla bla>",@"message",
@"<2000>",@"posixtime", nil];
NSArray* notifications = [NSArray arrayWithObjects:dictionary, nil];
NSError *writeError = nil;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:notifications options:NSJSONWritingPrettyPrinted error:&writeError];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(@"JSON Output: %@", jsonString);
return jsonString;
}
I would expect to get something like this:
{
"from" : "<xx3-xxxx>"
"to" : "<xxx-xxx>",
"message" : "<Bla bla bla>",
"posixtime" : "<2000>",
}
But I get a different order:
{
"posixtime" : "<2000>", <----- INCORRECT
"to" : "<xxx-xxx>",
"message" : "<Bla bla bla>",
"from" : "<xx3-xxxx>" <----- INCORRECT
}
How can I get the output in the same order as I insert it into the arrays?
[NSDictionary dictionaryWithObjectsAndKeys: //I want it to be:
@"<xx3-xxxx>",@"from", //1st
@"<xxx-xxx>",@"to", //2nd
@"<Bla bla bla>",@"message", //3rd
@"<2000>",@"posixtime", nil]; //4th