ABD
ABD

Reputation: 133

How to create JSON in alphabetical order by its KEY (Java)

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!

Upvotes: 9

Views: 11864

Answers (4)

Andrew Feng
Andrew Feng

Reputation: 1970

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;
  }

}

Upvotes: 0

Cousin Roy
Cousin Roy

Reputation: 211

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){
    } 

Upvotes: 2

lucas kim
lucas kim

Reputation: 910

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"}

Upvotes: 9

MrMisery
MrMisery

Reputation: 426

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<>();

Upvotes: 0

Related Questions