Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONObject sorted map params

Tags:

java

json

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?

like image 432
Giymose Avatar asked Oct 19 '22 06:10

Giymose


1 Answers

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.

like image 131
Tagir Valeev Avatar answered Nov 02 '22 08:11

Tagir Valeev