5

I'm getting JSON, but it's not in alphabetical order. How to sort json by it's KEY ? JSON:

{"b":"3","c":"1","a":"4"}

Expected output:

{"a":"4","b":"3","c":"1"}

Please help me to solve this problem. I really appreciate your help! Thanks!

ABD
  • 93
  • 3
  • 12
  • You can extract the data into an ArrayList and then sort with a comparator. – Tushar Sharma Mar 11 '17 at 07:59
  • Simply - convert your json data into a HashMap - Sort the HashMap - Convert it back to JsonObject. Purpose served, code it your self and revert back if you face any challange. – Pratik Ambani Mar 11 '17 at 13:15

3 Answers3

7

You can use the jackson library.

First add a jackson to the maven dependency.

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.8.7</version>
    </dependency>

Then use the code below.

    String jsonData = "{\"e\":\"6\",\"f\":\"1\",\"b\":\"3\",\"c\":\"1\",\"a\":\"4\"}";
    ObjectMapper om = new ObjectMapper();
    om.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
    Map<String, Object> map = om.readValue(jsonData, HashMap.class);
    String json = om.writeValueAsString(map);
    System.out.println(json); // result : {"a":"4","b":"3","c":"1","e":"6","f":"1"}

When I test it, I get output in sorted form.

{"a":"4","b":"3","c":"1","e":"6","f":"1"}

Ian Gustafson
  • 142
  • 2
  • 13
lucas kim
  • 830
  • 1
  • 10
  • 23
  • 1
    I was missing some code. Add the following line to the third line. om.configure (SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); – lucas kim Mar 11 '17 at 12:23
  • 1
    Warning - https://stackoverflow.com/questions/34817541/json-order-map-entries-by-keys-not-working-consistently – Javo Dec 04 '19 at 13:06
1

So here is one of solution to sort JSON object by key alphabetically without using external libraries(for Android Studio). The sortedJSON is the one with key sorted alphabetically.

try{
        JSONObject jo = new JSONObject();
        
        jo.put("g", "9");
        jo.put("t", "8");
        jo.put("r", "7");
        jo.put("d", "6");
        jo.put("c", "5");
        jo.put("b", "4");
        jo.put("a", "1");

        Map<String, String> joToMap = new HashMap<>();

        Iterator<String> keysItr = jo.keys();
        while (keysItr.hasNext()) {
            String key = keysItr.next();
            Object value = jo.get(key);

            joToMap.put(key, value.toString()); //since value is string so convert toString; depend on your value type
        }

        Map<String, String> sortedMap = new TreeMap<>(joToMap); //this will auto-sort by key alphabetically

        JSONObject sortedJSON = new JSONObject(); //recreate new JSON object for sorted result

        for (Map.Entry<String, String> entry : sortedMap.entrySet()) {
            sortedJSON.put(entry.getKey(), entry.getValue());
            // result will be {"a":"1","b":"4","c":"5","d":"6","g":"9","r":"7","t":"8"}
        }
    } catch (Exception e){
    } 
Cousin Roy
  • 161
  • 1
  • 6
0

You can use maps for this purpose , then sort the map according to the map key. after that insert it into the JSON object. In your case declare the map as:

Map<String,Integer> mapName = new HashMap<>();
MrMisery
  • 368
  • 8
  • 17
  • I have updated my question, please take a look, and help me, Thanks! – ABD Mar 11 '17 at 07:51
  • 1
    still it's the same way to solve this . store the results firstly in a map , then sort the map after that using loops put the map content into the JSON object. – MrMisery Mar 11 '17 at 07:56