简体   繁体   English

如何从iOS中的Web服务调用禁用自动排序JSON词典响应

[英]how to disable auto sorting JSON dictionary response from web service call in iOS

I am using one web service in my app. 我在我的应用程序中使用了一项Web服务。 Unfortunately I am not expecting the response to be auto sorted based on the keys. 不幸的是,我不希望响应会根据键自动排序。 I need the original response as it is in web. 我需要原始回复,就像在网络上一样。 Can anyone let me know how to do this in iOS app.I am using the following code to show the response. 任何人都可以让我知道如何在iOS应用中执行此操作。我正在使用以下代码来显示响应。

NSDictionary *response  = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];

JSON objects have unordered keys. JSON对象具有无序的键。 iOS is not sorting the keys in the data structure. iOS并未对数据结构中的键进行排序。 It's just sorting them when you print out the result (for convenience). 它只是在打印结果时对它们进行排序(为方便起见)。 Internal to the data structure, there is no guaranteed order. 在数据结构内部,没有保证的顺序。 It depends on how things hash. 这取决于事物如何散列。

There is no way to use NSJSONSerialization to create an "ordered dictionary" since ordered dictionaries don't exist in JSON. 由于JSON中不存在有序字典,因此无法使用NSJSONSerialization创建“有序字典”。 The way you fix this is to use a list of dictionaries, such as: 解决此问题的方法是使用词典列表,例如:

[ { "First": "A" }, { "Second", "B" } ]

This is promised to stay in order because it's a list. 因为这是一个列表,所以承诺将保持秩序。

If you can't change the format, and the format relies on order, then it's not proper JSON and you'll have to parse it some other way. 如果您不能更改格式,并且格式依赖于顺序,那么它不是正确的JSON,则必须以其他方式进行解析。 Typically I try to do simple string parsing (splitting on newlines for instance) to find large valid JSON "chunks" that can be handed to the parser. 通常,我尝试执行简单的字符串解析(例如,在换行符上进行拆分),以找到可以传递给解析器的大型有效JSON“块”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM