如何在JSONObject中保留LinkedHashMap的顺序?

4
我有一个带有状态的LinkedHashMap
Map<String, String> stateMap = new LinkedHashMap<String, String>();
// ...

我正在创建一个基于它的JSONObject。
JSONObject json = new JSONObject();
json.putAll(stateMap);

然而,条目似乎是无序的。我想保留LinkedHashMap在JSONObject中的顺序。我该如何实现这一点?

我认为你应该使用TreeMap而不是LinkedHashMap,但它会按Key的值对Map进行排序,而你想要按Value进行排序,因此你必须使用Comparator。以下是一些参考链接,用于按Value排序Map。http://www.mkyong.com/java/how-to-sort-a-map-in-java/http://www.programcreek.com/2013/03/java-sort-map-by-value/ - Darshit
1个回答

1
JSONObject不同,JSONArray是一个有序的值序列。因此,如果您想保留映射的顺序,可以使用两个键构建json对象。
  • The first key can be called data and will hold your stateMap data like this :

    json.element('data', stateMap)
    
  • The second key can be called keys and it will be a JSONArray object which will hold the ordered list of your map keys like this :

    JSONArray array = new JSONArray();
    array.addAll(stateMap.keySet())
    json.put('keys', array)
    

更多信息:


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接