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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With