在Hibernate管理的实体中考虑此属性:
@JsonFormat(pattern = "HH:mm")
@Column(name = "start_time")
private java.sql.Time startTime;
我将一个JSON对象作为@RequestBody发布到一个Spring控制器,Jackson应该映射到一个实体的实例(pojo).
杰克逊显然没有设法将时间字符串反序列化为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
我怎样才能指示杰克逊明白该怎么做?
解决方法:
解决方案是滚动自己的反序列化器:
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 {
@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")
private Time startTime;
标签:java,json,spring-mvc,hibernate,jackson
来源: https://codeday.me/bug/20190724/1524671.html