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

如何通过默认配置将浮点型时间戳反序列化为LocalDateTime?

解决浮点型时间戳转LocalDateTime的反序列化错误

错误原因

JavaTimeModule默认的LocalDateTime反序列化器不支持浮点数字输入,它仅接受ISO格式字符串、日期分量数组或长整型数字,因此遇到浮点型时间戳时会抛出类型不匹配异常。

解决方案(无需自定义反序列化器)

方案1:用Instant接收时间戳,再转换为LocalDateTime

Instant的内置反序列化器支持解析浮点型时间戳(将数值视为从1970-01-01T00:00:00Z开始的秒数,小数部分对应纳秒),之后可通过时区转换为LocalDateTime。

修改DTO类:

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Dto {
    @JsonFormat(shape = JsonFormat.Shape.NUMBER_FLOAT)
    private Instant timestamp;

    // 根据业务需求指定时区,示例用系统默认时区
    public LocalDateTime getDate() {
        return timestamp.atZone(ZoneId.systemDefault()).toLocalDateTime();
    }
}

反序列化代码保持不变:

ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
var dto = mapper.readValue(json, Dto.class);

方案2:配置ObjectMapper并调整字段注解

如果必须在DTO中直接保留LocalDateTime字段,可通过指定内置的InstantDeserializer,并配置时区完成转换:

修改DTO类:

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public class Dto {
    @JsonDeserialize(using = InstantDeserializer.class)
    private LocalDateTime date;
}

调整ObjectMapper配置(指定时区,确保转换正确):

ObjectMapper mapper = new ObjectMapper()
        .registerModule(new JavaTimeModule())
        .setTimeZone(TimeZone.getDefault());
var dto = mapper.readValue(json, Dto.class);

注:此方案依赖Jackson内置的InstantDeserializer,无需自行编写反序列化逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 22:39:18