yglodt yglodt - 2 months ago 10
Java Question

Jackson and java.sql.Time serialization / deserialization

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?

Answer

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(final JsonParser jp, final 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;