I have a Map, which contains String keys and String and integers values. I put values into the map as follows:
Map map = new LinkedHashMap();
map.put("b", 1);
map.put("a", 2);
After this, I added the map into a List:
List out = new LinkedList();
out.add(map);
And after that, I'm created a JSONObject
and put the List into it:
org.json.JSONObject json = new org.json.JSONObject();
json.put("header", "header");
json.put("array", out);
But if I do this, I see this json structure:
{"header":"header", "array":[{"a":2,"b":1}]}
But I want to see:
{"header":"header","array":[{"b":1,"a":2}]}
Where did I go wrong? Maybe this isn't the correct way?
If you want to keep the order, you should not use org.json
library as it stores the data in HashMap, so any order you want to preserve will be ignored. There's no easy way to fix this with org.json
. I'd suggest you to use another JSON library (GSON, Jackson, minimal-json, etc.). Almost any other library preserves the insertion order like LinkedHashMap
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With