2

I am trying to sort below array node within my json payload. Should be sort by name element

Before:

"empData": [
    {
      "name": "Jhon",
      "age": 33
    },
    {
      "name": "Sam",
      "age": 24
    },
    {
      "name": "Mike",
      "age": 65
    },
    {
      "name": "Jenny",
      "age": 33
    }
  ]

Expected:

"empData": [
    {
      "name": "Jenny",
      "age": 33
    },
    {
      "name": "Jhon",
      "age": 33
    },
    {
      "name": "Mike",
      "age": 65
    },
    {
      "name": "Sam",
      "age": 24
    }
  ]

I was trying below option:

private static final ObjectMapper SORTED_MAPPER = new ObjectMapper();

static {
    SORTED_MAPPER.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true);
}

public static JsonNode sortJsonArrayList(final JsonNode node) throws IOException {
    final Object obj = SORTED_MAPPER.treeToValue(node, Object.class);
    final String json = SORTED_MAPPER.writeValueAsString(obj);
    return objectMapper.readTree(json);
}

But not sure how to select name key for sorting.

2 Answers 2

3

Try something like this:

public JsonNode some(JsonNode node){
        //find list of objects that contains field name
        List<JsonNode> dataNodes = node.findParents("name");
        //sort it
        List<JsonNode> sortedDataNodes = empDataNodes
                .stream()
                .sorted(Comparator.comparing(o -> o.get("name").asText()))
                .collect(Collectors.toList());
        //return the same Json structure as in method parameter
        ArrayNode arrayNode = objectMapper.createObjectNode().arrayNode().addAll(sortedEmpDataNodes);
        return objectMapper.createObjectNode().set("empData", arrayNode);
}

You can debug it step by step and see how it works.

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

3 Comments

Can we have same approach to sort with two keys?
You can check this answer and add some of it solution in .sorted() method
Thanks. found stackoverflow.com/a/8036545/2303693 also which does the work perfectly
2

ORDER_MAP_ENTRIES_BY_KEYS is the feature which enables Map sorting by Map keys. As your result type is not a Map this sorting will not be applied. To sort array you can create custom deserialiser or sort deserialised array in place. This answer describes how this can be achieved.

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.