JSON格式:以正确的顺序获取输出 [英] JSON format: getting output in the correct order

查看:263
本文介绍了JSON格式:以正确的顺序获取输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

常见任务,将字符串转换为JSON格式.是的,很简单,有关StackOverflow的很多答案.

Common task, converting strings to a JSON format. Yes, easy, plenty of answers on StackOverflow about this.

我不容易理解的是为什么我得到的顺序与将配对对象放入NSDictionary中的顺序不同的原因.

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.

那是我写的代码:

-(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  
  }

如何获得与将其插入阵列的顺序相同的输出?

[NSDictionary dictionaryWithObjectsAndKeys:                  //I want it to be:
                                    @"<xx3-xxxx>",@"from",         //1st
                                    @"<xxx-xxx>",@"to",            //2nd
                                    @"<Bla bla bla>",@"message",   //3rd
                                    @"<2000>",@"posixtime", nil];  //4th

推荐答案

NSDictionary中的键/值对没有顺序.您可以按此顺序添加它们,但是词典中不保留任何订单信息.因此,当您创建JSON时,它会以任意顺序显示.

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.

如果您需要按特定顺序排列内容,则要么不使用字典,要么按所需顺序将项目流式传输到JSON(例如,使用

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

这篇关于JSON格式:以正确的顺序获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆