杰克逊仅使用字段名称对响应进行排序 [英] jackson to sort the response by using the field name alone

查看:76
本文介绍了杰克逊仅使用字段名称对响应进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个pojo课程. 使用Jackson的@JsonUnwrapped批注省略了类名,但属性未按我的期望排序.

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.

例如:

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

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

我的实际回答是:

{
c:1
a:2
d:2
}

但是我的预期答复是:

{
a:2
c:1
d:2
}

如何使响应中的字段按名称排序?

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

推荐答案

这有点棘手,因为Jackson将未包装对象的所有属性的序列化组合在一起. @JsonPropertyOrder注释无法覆盖此行为,因为它在未包装的字段上起作用,而不是字段的属性.解决方法是,您可以将对象序列化为中间的Map,自己对其进行排序,然后将其序列化为JSON,如下所示:

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

这篇关于杰克逊仅使用字段名称对响应进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆