我有一些以秒为单位的时间戳(即Unix时间戳)的JSON:
{"foo":"bar","timestamp":1386280997}
要求Jackson将其反序列化为带有DateTime字段的对象作为时间戳,结果是在1970-01-17T01:11:25.983Z该时间段后不久的某个时间,因为Jackson假设它以 毫秒为单位 。除了撕开JSON并添加一些零外,我如何让Jackson理解 秒 时间戳?
1970-01-17T01:11:25.983Z
我编写了一个自定义反序列化器,以秒为单位处理时间戳(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 } }