gpt4 book ai didi

java - Jackson 和 java.sql.Time 序列化/反序列化

转载 作者:搜寻专家 更新时间:2023-11-01 01:32:17 24 4
gpt4 key购买 nike

Hibernate 管理的实体中考虑这个属性:

@JsonFormat(pattern = "HH:mm")
@Column(name = "start_time")
private java.sql.Time startTime;

我将 JSON 对象作为 @RequestBody 发布到 Spring Controller,Jackson 应该映射到实体的实例( pojo).

Jackson 显然无法将时间字符串反序列化为 java.sql.Time,因为我得到了这个异常:

.w.s.m.s.DefaultHandlerExceptionResolver : Failed to read HTTP message:
org.springframework.http.converter.HttpMessageNotReadableException:
Could not read document: Can not construct instance of java.sql.Time,
problem: null

我如何指示 Jackson 了解该做什么?

最佳答案

解决方案是推出自己的反序列化器:

import java.io.IOException;
import java.sql.Time;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;

public class SqlTimeDeserializer extends JsonDeserializer<Time> {

@Override
public Time deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
return Time.valueOf(jp.getValueAsString() + ":00");
}
}

然后在实体中:

@JsonFormat(pattern = "HH:mm")
@JsonDeserialize(using = SqlTimeDeserializer.class)
@Column(name = "start_time")
private Time startTime;

关于java - Jackson 和 java.sql.Time 序列化/反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777194/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com