我有几个 pojo 类。
使用 Jackson @JsonUnwrapped
注释来省略类名,但属性没有按我期望的方式排序。
例如:
class a {
@JsonUnwrapped
B b;
int c;
//getters and setters
}
class B {
int a;
int d;
// getters and setters
}
我的实际 react 是:
{
c:1
a:2
d:2
}
但我预期的回应是:
{
a:2
c:1
d:2
}
如何才能使响应中的字段按名称排序?
最佳答案
这有点棘手,因为 Jackson 将解包对象的所有属性的序列化组合在一起。 @JsonPropertyOrder
注释无法覆盖此行为,因为它 works on the unwrapped field而不是字段的属性。作为解决方法,您可以将对象序列化为中间 Map
,自行排序,然后将其序列化为 JSON,如下所示:
ObjectMapper objectMapper = new ObjectMapper();
Map map = objectMapper.convertValue(new a(), Map.class);
SortedMap sortedMap = new TreeMap(map);
System.out.println(objectMapper.writeValueAsString(sortedMap));
关于java - jackson 单独使用字段名称对响应进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34487793/