使用 Gson 反序列化 Java 8 LocalDateTime

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22310143/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 14:51:38  来源:igfitidea点击:

Java 8 LocalDateTime deserialized using Gson

javajsonjava-8gson

提问by fische

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.

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

When I tried to deserialize, I get the error:

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

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING

回答by Randula

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.

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

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

使用 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());
        return LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
    }
}).create();

回答by Evers

To extend @Randula's answer, to parse a zoned date time string (2014-03-10T18:46:40.000Z) to JSON:

要扩展@Randula 的答案,将分区日期时间字符串 (2014-03-10T18:46:40.000Z) 解析为 JSON:

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() {
@Override
public LocalDateTime deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    return ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString()).toLocalDateTime();
}
}).create();

回答by nterry

To even further extend @Evers answer:

进一步扩展@Evers 答案:

You can further simplify with a lambda like so:

您可以使用 lambda 进一步简化,如下所示:

GSON GSON = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, (JsonDeserializer<LocalDateTime>) (json, type, jsonDeserializationContext) ->
    ZonedDateTime.parse(json.getAsJsonPrimitive().getAsString()).toLocalDateTime()).create();

回答by greenhorn

Following worked for me.

以下为我工作。

Java:

爪哇:

Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer<LocalDateTime>() { 
@Override 
public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { 

return LocalDateTime.parse(json.getAsString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm")); } 

}).create();

Test test = gson.fromJson(stringJson, Test.class);

where stringJsonis a Json which is stored as String type

其中stringJson是存储为 String 类型的 Json

Json:

杰森:

"dateField":"2020-01-30 15:00"

"dateField":"2020-01-30 15:00"

where dateFieldis of LocalDateTimetype which is present in the stringJson String variable.

其中dateFieldLocalDateTime类型,它存在于 stringJson 字符串变量中。