我有一些JSON的时间戳是秒(即Unix时间戳):
{"foo":"bar","timestamp":1386280997}
要求Jackson将其反序列化为一个带有时间戳DateTime字段的对象,结果是1970-01-17T01:11:25.983Z
,即纪元后不久的时间,因为Jackson假定它是milliseconds.除了撕开JSON并添加一些零,我怎样才能让Jackson理解seconds时间戳呢?
我有一些JSON的时间戳是秒(即Unix时间戳):
{"foo":"bar","timestamp":1386280997}
要求Jackson将其反序列化为一个带有时间戳DateTime字段的对象,结果是1970-01-17T01:11:25.983Z
,即纪元后不久的时间,因为Jackson假定它是milliseconds.除了撕开JSON并添加一些零,我怎样才能让Jackson理解seconds时间戳呢?
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
}
}
}
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
}
}