Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 988
yglodt Avatar asked Dec 25 '22 03:12

yglodt


2 Answers

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;
like image 77
yglodt Avatar answered Dec 28 '22 07:12

yglodt


You should try hh:mm:ss time format of java.sql.Time instead of hh:mm format. This will be better way to handle exception instead of overriding JsonDeserializer method.

like image 32
Maulik Kakadiya Avatar answered Dec 28 '22 06:12

Maulik Kakadiya