如何反映杰克逊在几秒钟内的时间戳? [英] How do I deserialize timestamps that are in seconds with Jackson?
问题描述
我有一些JSON,其时间戳以秒为单位(即Unix时间戳):
I've got some JSON that has timestamps in seconds (i.e. a Unix timestamp):
{"foo":"bar","timestamp":1386280997}
要求Jackson将其反序列化为具有DateTime的对象时间戳的字段导致 1970-01-17T01:11:25.983Z
,这个时期后不久,因为杰克逊假设它在毫秒。除了撕掉JSON并添加一些零之外,我怎样才能让杰克逊理解秒时间戳?
Asking Jackson to deserialize this into an object with a DateTime field for the timestamp results in 1970-01-17T01:11:25.983Z
, a time shortly after the epoch because Jackson is assuming it to be in milliseconds. Aside from ripping apart the JSON and adding some zeros, how might I get Jackson to understand the seconds timestamp?
推荐答案
我写了一个自定义反序列化以秒为单位处理时间戳(Groovy语法)。
I wrote a custom deserializer to handle timestamps in seconds (Groovy syntax).
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将其用于时间戳:
And then I annotated my POGO to use that for the timestamp:
class TimestampThing {
@JsonDeserialize(using = UnixTimestampDeserializer.class)
DateTime timestamp
@JsonCreator
public TimestampThing(@JsonProperty('timestamp') DateTime timestamp) {
this.timestamp = timestamp
}
}
这篇关于如何反映杰克逊在几秒钟内的时间戳?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!