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

Android端POST请求报错:无法反序列化LocalDateTime类型值

问题根源

后端SpringBoot期望接收字符串格式的日期参数,但你的Android代码直接将LocalDateTime对象序列化,导致请求体中date字段变成了包含year、month等子字段的JSON对象(而非字符串),Jackson无法将这种对象结构反序列化为LocalDateTime类型,因此抛出MismatchedInputException。而Angular端是将日期转为符合后端要求的字符串格式,所以能正常请求。

解决方案

根据你使用的JSON序列化库,选择对应处理方式:

1. 使用Gson序列化(Retrofit默认常用配置)

自定义LocalDateTime序列化器,将对象转为后端期望的字符串格式:

public class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(FORMATTER.format(src));
    }
}

创建Gson实例时注册该序列化器:

Gson gson = new GsonBuilder()
        .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeSerializer())
        .create();

将配置好的Gson传入Retrofit:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

2. 使用Jackson序列化

配置Jackson的JavaTimeModule,指定LocalDateTime的序列化格式:

ObjectMapper objectMapper = new ObjectMapper();
JavaTimeModule module = new JavaTimeModule();
module.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
objectMapper.registerModule(module);

将该ObjectMapper传入Retrofit的Jackson转换器:

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .addConverterFactory(JacksonConverterFactory.create(objectMapper))
        .build();

3. 极简方案:直接传递格式化后的字符串

在构建请求体前,提前将LocalDateTime转为字符串:

// 解析后直接格式化为字符串
String dateStr = date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
// 将dateStr放入请求体的date字段中
验证要点

修改后,请求体中的date字段应呈现为类似"2022-02-02 10:00:00"的字符串格式,与Angular端的请求结构一致,即可被后端正常解析。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 23:45:34