4

I have a LinkedHashMap with states.

Map<String, String> stateMap = new LinkedHashMap<String, String>();
// ...

I'm creating a JSONObject based on it.

JSONObject json = new JSONObject();
json.putAll(stateMap);

However, the entries appear unordered. I'd like to preserve the ordering of LinkedHashMap in JSONObject. How can I achieve this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • I think you should use TreeMap instead of LinkedHashMap but it will sort your map by value of Key and you want to sort it by Value so you have to use Comparator. Here are some reference links for sorting Map by value instead of Key. http://www.mkyong.com/java/how-to-sort-a-map-in-java/ http://www.programcreek.com/2013/03/java-sort-map-by-value/ – Darshit May 25 '16 at 09:33

1 Answers1

1

Unlike JSONObject, JSONArray is an ordered sequence of values. So if you want to preserve the order of your map, you can construct your json object with two keys:

  • 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)
    

For more information :

tfosra
  • 581
  • 5
  • 12