You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 11:22:24