【问题标题】:xcode sorting json in alphabetical when should not be sorting at all当根本不应该排序时,xcode按字母顺序排序json
【发布时间】:2014-10-02 20:40:11
【问题描述】:

我有一个脚本似乎将生成的 JSon 排序为其他顺序。

一个php脚本输出的json是这样的

{result:
    {pizza:
        {more nodes etc.....
         }
    },
    {pasta:
        {more nodes etc.....
         }
    },
    {sides:
        {more nodes etc.....
         }
    },
    {salads:
        {more nodes etc.....
         }
    },  
    {desserts:
         {more nodes etc.....
         }
    }
}

然后我在 Xcode 中使用这段代码进行 JSon 序列化:

 NSMutableDictionary *res = [NSJSONSerialization JSONObjectWithData:receivedData options:NSJSONReadingMutableLeaves error:&myError];

如果我在控制台中显示结果,json 按字母顺序列出(不是原始输出),就像这样

{result:
    {desserts:
         {more nodes etc.....
         }
    },
    {pasta:
        {more nodes etc.....
         }
    },
    {pizza:
        {more nodes etc.....
         }
    },
    {salads:
        {more nodes etc.....
         }
    },  
    {sides:
        {more nodes etc.....
         }
    }


}

此时我的代码中没有任何排序选项,如您所见,它已对 json 结果进行了排序

如果我运行这段代码只显示键:

NSLog(@"data %@",[[res objectForKey:@"results"]allKeys]);

我得到了这个结果:

data (
    pasta,
    pizza,
    sides,
    salad,
    desserts
)

按字母顺序将第一个元素放在底部

我根本不想要任何排序,因为排序已由 php 脚本处理

有什么想法吗?

【问题讨论】:

    标签: json xcode sorting


    【解决方案1】:

    这不是 JSON,它是 NSMutableDictionary。字典没有顺序,显示代码正在做你看到的排序。

    如果您想要一个必须在 JSON 中显式提供的订单,则字典项目的顺序不足以指定订单。

    或者,您可以自己解析 JSON 以确定顺序,但该顺序必须在字典之外进行维护。也许在一个相关的字典键名数组中。

    【讨论】:

    • 数据在 uitableview 中的显示方式相同。如果我使用 valueAtIndex:0 它选择与上面的列表相同
    • 但是NSMutableDictionary 没有方法:valueAtIndex:0。如果您要索引到一个键数组并且您得到的顺序只是偶然的。
    • 你能推荐使用 NSMutableDictionary 以外的东西吗?
    • 来自 Apple 的 allKeys 方法文档:“数组中元素的顺序未定义。”
    • 检查 CocoaPods 中的“ORDERED DICTIONARY*”。但是你必须找到另一种 JSON 解析方法。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 2011-01-30
    相关资源
    最近更新 更多