When JsonObject's keys are iterated they aren't in the same order as in the response from the server

前端 未结 3 589
滥情空心
滥情空心 2020-12-03 04:56

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 is

3条回答
  •  一向
    一向 (楼主)
    2020-12-03 05:38

    You can use Sorted map to put keys and values into. Something like this

     public static List listFromJsonSorted(JSONObject json) {
        if (json == null) return null;
        SortedMap map = new TreeMap();
        Iterator i = json.keys();
        while (i.hasNext()) {
            try {
                String key = i.next().toString();
                JSONObject j = json.getJSONObject(key);
                map.put(key, j);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    
        return new LinkedList(map.values());
    }
    

提交回复
热议问题