JSON format: getting output in the correct order [duplicate]

。_饼干妹妹 提交于 2020-01-03 03:16:10

问题


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

回答1:


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).



来源:https://stackoverflow.com/questions/21973422/json-format-getting-output-in-the-correct-order

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!