简体   繁体   English

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM