本文介绍了Jackson和java.sql.Time序列化/反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
@JsonFormat(pattern =HH:mm)
@Column(name =start_time)
private java.sql.Time startTime;
我发布 c> Jackson >
Jackson 显然不能将时间字符串反序列化为 java.sql。 Time ,因为我得到这个异常:
.wsmsDefaultHandlerExceptionResolver:无法读取HTTP消息:
org.springframework.http.converter.HttpMessageNotReadableException:
无法读取文档:无法构造java.sql.Time实例,
问题: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;
公共类SqlTimeDeserializer扩展了JsonDeserializer< Time> {
$ b $ @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)
私人时间startTime;
Consider this property in an Hibernate-managed entity:
@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).
Jackson does apparently not manage to de-serialize the time-string into a java.sql.Time, because I am getting this Exception:
.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?
解决方案
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;
这篇关于Jackson和java.sql.Time序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!