我有一些 JSON,其时间戳以秒为单位(即 Unix 时间戳):
{"foo":"bar","timestamp":1386280997}
要求 Jackson 将其反序列化为一个带有 DateTime 字段作为时间戳的对象,结果是1970-01-17T01:11:25.983Z
,纪元之后不久的时间,因为杰克逊假设它位于毫秒。除了分解 JSON 并添加一些零之外,我怎样才能让 Jackson 理解seconds时间戳?
我写了一个自定义解串器 http://fasterxml.github.io/jackson-databind/javadoc/2.3.0/com/fasterxml/jackson/databind/JsonDeserializer.html处理以秒为单位的时间戳(Groovy 语法)。
class UnixTimestampDeserializer extends JsonDeserializer<DateTime> {
Logger logger = LoggerFactory.getLogger(UnixTimestampDeserializer.class)
@Override
DateTime deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
String timestamp = jp.getText().trim()
try {
return new DateTime(Long.valueOf(timestamp + '000'))
} catch (NumberFormatException e) {
logger.warn('Unable to deserialize timestamp: ' + timestamp, e)
return null
}
}
}
然后我注释了我的 POGO 以将其用作时间戳:
class TimestampThing {
@JsonDeserialize(using = UnixTimestampDeserializer.class)
DateTime timestamp
@JsonCreator
public TimestampThing(@JsonProperty('timestamp') DateTime timestamp) {
this.timestamp = timestamp
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)