使用Gson反序列化Java 8 LocalDateTime

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

当我尝试反序列化时,我收到错误:

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING 

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

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

 Gson gson = new GsonBuilder().registerTypeAdapter(LocalDateTime.class, new JsonDeserializer() { @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(); 

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

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

甚至进一步扩展@Evers答案:

您可以使用lambda进一步简化:

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