频道
bg

Jackson转换TimeStamp时空字串的问题

coding五月 21, 20161mins
经验错误

问题H2

当使用Jackson进行json数据转换时,如果目标字段类型为TimeStamp并且要转换的值为空字串时会报空指针错误。

原因H2

下面是Timestamp反序列化器的代码

bash

public static class TimestampDeserializer extends DateBasedDeserializer<Timestamp>
{
public TimestampDeserializer() { super(Timestamp.class); }
public TimestampDeserializer(TimestampDeserializer src, DateFormat df, String formatString) {
super(src, df, formatString);
}
@Override
protected TimestampDeserializer withDateFormat(DateFormat df, String formatString) {
return new TimestampDeserializer(this, df, formatString);
}
@Override
public java.sql.Timestamp deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException
{
return new Timestamp(_parseDate(jp, ctxt).getTime());
}
}

通过_parseDate方法转换为Date后,并没有判断是否转换成功而直接调用了getTime方法。

解决H2

添加一个自定义的TimeStamp的Deserializer,然后通过SimpleModule来注册到ObjectMapper中。

评论


新的评论

匹配您的Gravatar头像

Joen Yu

@2022 JoenYu, all rights reserved. Made with love.