[英]Jackson and java.sql.Time serialization / deserialization
Consider this property in an Hibernate
-managed entity: 在
Hibernate
管理的实体中考虑以下属性:
@JsonFormat(pattern = "HH:mm")
@Column(name = "start_time")
private java.sql.Time startTime;
I post a JSON
-object as @RequestBody
to a Spring Controller which Jackson
is supposed to map into an instance of the entity (pojo). 张贴一
JSON
-object作为@RequestBody
到弹簧控制器,其Jackson
应该映射到实体(POJO)的一个实例。
Jackson
does apparently not manage to de-serialize the time-string into a java.sql.Time
, because I am getting this Exception: 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
How can I instruct Jackson
to understand what to do? 我如何指导
Jackson
了解该怎么办?
The solution is to roll your own deserializer: 解决方案是使用您自己的解串器:
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");
}
}
And then in the entity: 然后在实体中:
@JsonFormat(pattern = "HH:mm")
@JsonDeserialize(using = SqlTimeDeserializer.class)
@Column(name = "start_time")
private Time startTime;
You should try hh:mm:ss
time format of java.sql.Time
instead of hh:mm
format. 您应该尝试使用
java.sql.Time
hh:mm:ss
时间格式,而不是hh:mm
格式。 This will be better way to handle exception instead of overriding JsonDeserializer
method. 这将是处理异常而不是重写
JsonDeserializer
方法的JsonDeserializer
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.