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

SpringBoot调用外部API遇Jackson反序列化异常,求正确DTO结构

解决Jackson反序列化MismatchedInputException问题

你的DTO类结构和API返回的JSON层级完全不匹配,导致Jackson无法正确解析。先拆解API返回的JSON结构:

{
  "personsData": {  // 根字段,值是一个Map,key为日期字符串,value为Person对象列表
    "2023-02-27": [  // 日期作为key,对应Person数组
      {"country": "INDIA","age": 19,"updated_at": "2022-06-24T00:00:11.483Z"},
      ...
    ],
    "2023-02-25": [
      ...
    ]
  }
}

以下是匹配该JSON的正确Java类结构:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

public class HistoricalApiResponse {
    // 对应JSON中的personsData字段
    @JsonProperty("personsData")
    private Map<String, List<Person>> personsData;

    // getter和setter
    public Map<String, List<Person>> getPersonsData() {
        return personsData;
    }

    public void setPersonsData(Map<String, List<Person>> personsData) {
        this.personsData = personsData;
    }
}

class Person {
    private Integer age;
    private String country;

    // 对应JSON中的updated_at字段,用LocalDateTime替代过时的Date
    @JsonProperty("updated_at")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    private LocalDateTime updatedAt;

    // getter和setter
    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public LocalDateTime getUpdatedAt() {
        return updatedAt;
    }

    public void setUpdatedAt(LocalDateTime updatedAt) {
        this.updatedAt = updatedAt;
    }
}

关键说明

  1. 根类结构:HistoricalApiResponse直接包含personsData字段,类型为Map<String, List<Person>>,完全匹配JSON中「日期为key、Person列表为value」的结构
  2. 字段映射:Person类用@JsonProperty("updated_at")解决JSON下划线命名和Java驼峰命名的不匹配问题
  3. 日期处理:用LocalDateTime替代过时的Date,配合@JsonDeserialize确保Jackson正确解析ISO格式的日期字符串(SpringBoot默认已引入jackson-datatype-jsr310依赖支持该类型)

可选:使用Date类型的替代方案

如果一定要用Date,可以替换LocalDateTime相关代码为:

@JsonProperty("updated_at")
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
private Date updatedAt;

内容的提问来源于stack exchange,提问作者SmlCodes

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 12:57:30