devanathan
devanathan

Reputation: 818

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?

Upvotes: 3

Views: 1499

Answers (1)

heenenee
heenenee

Reputation: 20125

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));

Upvotes: 2

Related Questions