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
有帮助吗?

解决方案

The key/value pairs in an NSDictionary have no order. You may add them in that order but no order information is maintained inside the dictionary. So, when you create the JSON it comes out in an arbitrary order.

If you need the content in a certain order then you should either not use a dictionary or you should stream the items into the JSON in the order that you want (for example, with SBJson4StreamWriter).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top