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

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.