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

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

问题描述

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



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

$ p $ java.lang.IllegalStateException:预期BEGIN_OBJECT,但是STRING


解决方案

反序列化LocalDateTime属性,因为GSON无法解析属性的值,因为它不知道LocalDateTime对象。



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

  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());
返回LocalDateTime.ofInstant(instant,ZoneId.systemDefault());
}
})。create();


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

解决方案

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.

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天全站免登陆