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

Hibernate受管实体中考虑以下属性:

@JsonFormat(pattern = "HH:mm")

@Column(name = "start_time")

private java.sql.Time startTime;

我向Spring Controller

发布了一个JSON-object对象,@RequestBodyJackson对象应该映射到实体(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;

以上是 Jackson和java.sql.Time序列化/反序列化 的全部内容, 来源链接: utcz.com/qa/421445.html

回到顶部