Jackson反序列化:能否省略PhoneList类直接映射列表?
能否省略中间嵌套类完成Jackson反序列化?
给定如下JSON结构:
{ "name": "test", "phoneList": { "phone": [ { "number": 32323232, "code": 555 }, { "number": 4343423432, "code": 555 } ] } }
原适配DTO需要创建中间类PhoneList:
class Response { String name; PhoneList phoneList; static class PhoneList { List<Phone> phone = new ArrayList<>(); static class Phone { String number; Integer code; } } }
现在想简化DTO结构,去掉PhoneList类,直接在Response中定义List<Phone>类型的phoneList属性,期望的DTO结构如下:
class Response { String name; List<Phone> phoneList = new ArrayList<>(); static class Phone { String number; Integer code; } }
可以实现,只需要借助Jackson的@JsonProperty注解指定JSON字段的嵌套路径即可,具体修改如下:
class Response { String name; // 指定映射JSON中的"phoneList.phone"节点 @JsonProperty("phoneList.phone") List<Phone> phoneList = new ArrayList<>(); static class Phone { String number; Integer code; } }
说明:
@JsonProperty("phoneList.phone")告诉Jackson,当前phoneList字段需要映射到JSON中phoneList对象下的phone数组节点。- JSON中
number字段是数字类型,DTO中定义为String类型,Jackson默认会自动完成数字到字符串的转换,无需额外配置。
内容的提问来源于stack exchange,提问作者wuttke
相关产品推荐
相关产品推荐

