7

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
  • 113
  • 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
  • Do you want json order to be the same as insertion order in your code, or natural key order? – Bohemian Jul 12 '23 at 02:00

4 Answers4

8

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
  • 162
  • 2
  • 13
lucas kim
  • 890
  • 1
  • 11
  • 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
  • 2
    Warning - https://stackoverflow.com/questions/34817541/json-order-map-entries-by-keys-not-working-consistently – Javo Dec 04 '19 at 13:06
2

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
  • 191
  • 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
  • 406
  • 7
  • 19
  • 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
0

If you are like me just want to sort fields of json object by field name and do comparison to find the difference between json strings, here is the code snippet you can refer to:

public final class JsonTestUtils {

  private static void formalizeJson(String jsonStr, String fileName) throws IOException {
    Gson gson = new GsonBuilder().setPrettyPrinting().create();
    TreeMap<String, Object> map = gson.fromJson(jsonStr, TreeMap.class);
    sortMap(map);
    String jsonStrSorted = gson.toJson(map);
    FileUtils.writeStringToFile(new File(fileName), jsonStrSorted, StandardCharsets.UTF_8);
  }

  private static void sortMap(TreeMap<String, Object> map) {
    map.replaceAll((k, v) -> sortElement(v));
  }

  private static Object sortElement(Object element) {
    if (element instanceof List) {
      return ((List) element).stream()
          .map(JsonTestUtils::sortElement)
          .collect(Collectors.toList());
    }

    if (element instanceof Map) {
      TreeMap<String, Object> subNode = new TreeMap<>();
      subNode.putAll((Map) element);
      sortMap(subNode);
      return subNode;
    }

    return element;
  }

}
Andrew Feng
  • 1,912
  • 17
  • 20