使用 Gson 反序列化 Java 8 LocalDateTime [英] Java 8 LocalDateTime deserialized using Gson

查看:65
本文介绍了使用 Gson 反序列化 Java 8 LocalDateTime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有格式为2014-03-10T18:46:40.000Z"的日期时间属性的 JSON,我想使用 Gson 将其反序列化为 java.time.LocalDateTime 字段.

I have JSONs with a date-time attribute in the format "2014-03-10T18:46:40.000Z", which I want to deserialize into a java.time.LocalDateTime field using Gson.

当我尝试反序列化时,出现错误:

When I tried to deserialize, I get the error:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING

推荐答案

反序列化 LocalDateTime 属性时发生错误,因为 GSON 无法解析该属性的值,因为它不知道 LocalDateTime 对象.

The error occurs when you are deserializing the LocalDateTime attribute because GSON fails to parse the value of the attribute as it's not aware of the LocalDateTime objects.

使用 GsonBuilder 的 registerTypeAdapter 方法来定义自定义的 LocalDateTime 适配器.以下代码片段将帮助您反序列化 LocalDateTime 属性.

Use GsonBuilder's registerTypeAdapter method to define the custom LocalDateTime adapter. Following code snippet will help you to deserialize the LocalDateTime attribute.

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
    @Override
    public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
        Instant instant = Instant.ofEpochMilli(json.getAsJsonPrimitive().getAsLong());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}).create();

这篇关于使用 Gson 反序列化 Java 8 LocalDateTime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆