Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jackson to sort the response by using the field name alone

I have several pojo classes. The used the Jackson @JsonUnwrapped annotation to omit the class name but the properties are not sorting how I expect.

For Example:

class a {
    @JsonUnwrapped
    B b;
    int c;
    //getters and setters
}

class B {
    int a;
    int d;
    // getters and setters
}

My actual response is:

{
c:1
a:2
d:2
}

But my expected response is:

{
a:2
c:1
d:2
}

How can make it so that the fields in the response are sorted by name?

like image 855
devanathan Avatar asked Nov 27 '25 13:11

devanathan


1 Answers

This is a bit tricky because Jackson groups the serialization of all properties of the unwrapped object together. The @JsonPropertyOrder annotation can't override this behavior because it works on the unwrapped field and not the field's properties. As a workaround, you can serialize the object to an intermediate Map, sort it yourself, and then serialize it to JSON as follows:

ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.convertValue(new a(), Map.class);
SortedMap sortedMap = new TreeMap(map);
System.out.println(objectMapper.writeValueAsString(sortedMap));
like image 51
heenenee Avatar answered Nov 29 '25 01:11

heenenee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!