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?
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With