繁体   English   中英

如何使用gson以纳秒精度反序列化JSON日期时间

[英]How to deserialise JSON datetime with nanosecond precision using gson

我正在尝试使用gson反序列化一个JSON对象,但在日期方面遇到问题。 日期从JSON对象反序列化,但由于JSON对象中的值以纳秒为单位,因此我获得的值略微偏离预期值。

请参阅以下代码

JSONClass

public class JSONClass {
    private Date timestamp;

    public Date getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(Date timestamp) {
        this.timestamp = timestamp;
    }
}

主要

public class GsonTestApplication {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss.SSS").create();
        final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
        final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
        System.out.println(foo.getTimestamp().toString());
    }
}

应用程序的输出是

Thu Nov 09 11:08:39 GMT 2017

当我期待它

Thu Nov 09 11:07:20 GMT 2017

我不关心纳秒精度,所以我很高兴被截断,但由于我无法控制JSON格式,我不确定最好的方法。

如何让gson正确地反序列化日期?

这是Date可用精度的问题,对于Java 8,最好使用LocalDateTime 这也意味着你需要一个TypeAdapter因为Gson与LocalDateTime不能很好地协同工作。 需要在Gson中注册此类型适配器,以从String反序列化(并可能序列化) LocalDateTime对象。

像下面这样的东西应该给你你需要的东西。

JSONClass

public class JSONClass {
    private LocalDateTime timestamp;

    public LocalDateTime getTimestamp() {
        return timestamp;
    }

    public void setTimestamp(LocalDateTime timestamp) {
        this.timestamp = timestamp;
    }
}

LocalDateTimeDeserialiser

static class LocalDateTimeDeserializer implements JsonDeserializer<LocalDateTime> {

        private DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE_TIME;

        LocalDateTimeDeserializer(String datePattern) {
            this.formatter = DateTimeFormatter.ofPattern(datePattern);
        }

        @Override
        public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
            return LocalDateTime.parse(json.getAsString(), formatter);
        }

主要

public class GsonTestApplication {
    public static void main(String[] args) {
        final Gson gson = new GsonBuilder().(LocalDateTime.class, new LocalDateTimeDeserializer("yyyy-MM-dd HH:mm:ss.SSSSSSx")).create();
        final String responseJSON = "{ \"timestamp\":\"2017-11-09 11:07:20.079364+00\" }";
        final JSONClass foo = gson.fromJson(responseJSON, new TypeToken<JSONClass>(){}.getType());
        System.out.println(foo.getTimestamp().toString());
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM