java - 我如何反序列化以 jackson 为单位的时间戳?

我有一些以秒为单位的时间戳(即 Unix 时间戳)的 JSON:

{"foo":"bar","timestamp":1386280997}

要求 Jackson 将其反序列化为具有 DateTime 字段的对象以获取时间戳,结果为 1970-01-17T01:11:25.983Z,这是纪元之后不久的时间,因为 Jackson 假设它是毫秒。除了撕开 JSON 并添加一些零之外,我如何让 Jackson 理解 seconds 时间戳?

最佳答案

我写了一个自定义 deserializer以秒为单位处理时间戳(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
    }
}

https://stackoverflow.com/questions/20635698/

相关文章:

json - JSON 的正确 MIME 类型是什么?

ios - 如何让 NSJSONSerialization 将 boolean 值输出为真或假?

php - json_encode() 返回 false

javascript - 为什么有些对象文字属性被引用而有些则没有?

c# - 在 JSON.NET 中序列化/反序列化字节数组

ios - swift: 将多个 对象添加到 NSDictionary

ruby-on-rails - rails : include related object in

java - 如何从 JSON 对象中获取日期

python - 将 JSON 日期字符串转换为 Python 日期时间

java - 使用 Jackson 自定义 JSON 反序列化