当迭代JsonObject的密钥时,它们的顺序与服务器的响应顺序不同 [英] When JsonObject's keys are iterated they aren't in the same order as in the response from the server

查看:106
本文介绍了当迭代JsonObject的密钥时,它们的顺序与服务器的响应顺序不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从JSON字符串的服务器得到了非常大的响应。我将它转换为JSON对象,然后获取密钥并对其进行迭代。



问题在于,当我进行迭代时,它与服务器响应的顺序不同。 / p>

然后我通过添加 List< String> 中的所有键来应用另一种方法并对其进行排序然后获取它的迭代器,但它仍然不是我所要求的(如响应)。



代码示例在这里:

  JSONObject jsonObject = new JSONObject(responseString); 
Iterator< String> myIter = jsonObject.keys();


List< String> sortKey = new ArrayList< String>();

while(myIter.hasNext()){
sortKey.add(myIter.next());
}
Collections.sort(sortKey);


解决方案

JSON对象的键的顺序不是应该是有意义的。如果您需要特定订单,则应使用数组,而不是对象。



您的Java代码按字母顺序对键进行排序。无法获得对象中键的初始排序。



参考1


键的顺序未定义


参考2


对象是一组无序的名称/值对



I have a very large response from server of JSON string. I converted it to JSON object and then get the keys and iterate it.

The problem is that when I iterate it isnt in the same order as in response from server.

Next then I apply another method by adding all the keys in List<String> and the sort it and then get the iterator of that but still it isn't as I required (as in response).

Code example is here:

JSONObject jsonObject = new JSONObject(responseString);
    Iterator<String> myIter = jsonObject.keys();


    List<String> sortKey = new ArrayList<String>();

    while(myIter.hasNext()){
        sortKey.add(myIter.next());
    }
    Collections.sort(sortKey);

解决方案

The order of the keys of a JSON object is not supposed to be meaningful. If you want a specific order, you should use an array, not an object.

Your Java code sorts the keys alphabetically. There is no way to get the initial ordering of the keys in the object.

Reference 1:

The order of the keys is undefined

Reference 2:

An object is an unordered set of name/value pairs

这篇关于当迭代JsonObject的密钥时,它们的顺序与服务器的响应顺序不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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