How to save LinkedHashMap binding in JSONObject?

I have LinkedHashMapwith conditions.

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

I create on it JSONObject.

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

However, the entries look disordered. I would like to keep ordering LinkedHashMapin JSONObject. How can I achieve this?

+4
source share
1 answer

In contrast JSONObject, JSONArrayan ordered sequence of values. Therefore, if you want to keep the order of your map, you can create your object jsonwith two keys:

  • The first key can be called data and will contain your data stateMapas follows:

    json.element('data', stateMap)
    
  • , JSONArray, :

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

:

+1

All Articles