-3

I have a JSON array and want to sort it based on Key (alphanumeric) in Java.

[{"exe":"12"},{"pdf":"23"},{"abc":"56"},{"zqr":"9"},{"cpr":"15"}]

How to display it after sorting as:

[{"abc":"56"},{"cpr":"15"},{"exe":"12"},{"pdf":"23"},{"zqr":"9"}]
James Z
  • 12,209
  • 10
  • 24
  • 44
Abhinav Parashar
  • 619
  • 4
  • 11
  • 27

2 Answers2

0

This is a little ugly, but I couldn't think how to more cleanly deal with the arbitrary key thing. It does work:

    List<Map<String, String>> list = (List<Map<String, String>>)JsonEncodeDecode.decode("[{\"exe\":\"12\"},{\"pdf\":\"23\"},{\"abc\":\"56\"},{\"zqr\":\"9\"},{\"cpr\":\"15\"}]\n");
    list.sort(Comparator.comparing(a -> (String)a.keySet().toArray()[0]));
    System.out.println(JsonEncodeDecode.encode(list));

Result:

[{"abc":"56"},{"cpr":"15"},{"exe":"12"},{"pdf":"23"},{"zqr":"9"}]

I expect that you'd have some other way to come up with the initial list than to hard-code it into your code. This is just to show that the sort works.

CryptoFool
  • 21,719
  • 5
  • 26
  • 44
0

Setup your POM.XML with:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version><!-- or higher version -->
</dependency>

And Java code like that:

public static void main(String[] args) throws Exception {
    
    String json = "[{\"exe\":\"12\"},{\"pdf\":\"23\"},{\"abc\":\"56\"},{\"zqr\":\"9\"},{\"cpr\":\"15\"}]";
    ObjectMapper mapper = new ObjectMapper();
    List<LinkedHashMap> parsedJson = mapper.readValue(json, List.class);
    
    Map<String, String> sortedMap = new TreeMap<>();
    
    for (LinkedHashMap<String, String> elementMap : parsedJson) {
        Entry<String, String> elementEntry = elementMap.entrySet().iterator().next();
        sortedMap.put(elementEntry.getKey(), elementEntry.getValue());
    }
            
    System.out.println(mapper.writeValueAsString(sortedMap));
}

There might be better ways, but for now...