• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

iOS:JSON 乱序显示字典。如何提出重新排序?

[复制链接]
菜鸟教程小白 发表于 2022-12-13 07:30:11 | 显示全部楼层 |阅读模式 打印 上一主题 下一主题

假设我们有以下字典:

dict = [NSDictionary dictionaryWithObjectsAndKeys:
                [NSNumber numberWithInt:currentItem], @"item number",
                [NSNumber numberWithInt[[item valueForKey"section"] intValue]+1)], @"section number",
                currentDate, @"date of item",
                [NSNumber numberWithDouble:timeDifference], @"time difference in millis",
                        nil];

然后我得到以下输出:

{
  "time difference in millis" : 5.220093071460724,
  "section number" : 1,
  "date of item" : "28/04/2014 15:56:54,234",
  "item number" : 3
}

我使用以下代码将字典转换为 JSON:

NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
NSString *jsonString = [[NSString alloc] initWithBytes:[jsonData bytes] length:[jsonData length] encoding:NSUTF8StringEncoding]; 
jsonString = [jsonString stringByReplacingOccurrencesOfString"\\" withString""];

如何操作 JSON 字符串显示其键的顺序。例如,我想要:

{
  "item number" : 3,
  "section number" : 1,
  "date of item" : "28/04/2014 15:56:54,234",
  "time difference in millis" : 5.220093071460724
}

或者别的什么。关键是我想控制这个过程。我如何得到它?我的第一个想法是编写一个解析器,以我想要的方式显示排序。

这里有类似的问题,但我的重点是操纵顺序,而不是仅仅重新创建我从字典中放置它的顺序。

JSON format: getting output in the correct order

Need JSON document that is generated to be in same order as objects inserted in NSMutableDictionary in iOS



Best Answer-推荐答案


NSDictionary 没有按定义排序。 如果您想拥有相同的顺序,最简单的方法是将所有内容包装到 NSArray 中。

关于iOS:JSON 乱序显示字典。如何提出重新排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23343535/

回复

使用道具 举报

懒得打字嘛,点击右侧快捷回复 【右侧内容,后台自定义】
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注0

粉丝2

帖子830918

发布主题
阅读排行 更多
广告位

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap