JSON Gson的LocalDateTime和String转化

问题

JAVA8 StringLocalDateTime 报转换异常。

解决

写一个实现 JsonSerializerJsonDeserializer 接口的类。

public class LocalDateTimeAdapter implements JsonSerializer<LocalDateTime>, JsonDeserializer<LocalDateTime> {
  //序列化
  @Override
  public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
    return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
  }
  //反序列化
  @Override
  public LocalDateTime deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
    return LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    //下面这个也行,并且当时间带时区时就必须用下面这个
    //return ZonedDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString()).toLocalDateTime();
  }
}

创建 GSON

Gson gson = new GsonBuilder().setPrettyPrinting()//查看的时候好看些
        .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
        .create();

当然也可以使用 lambda 表达式实现。

//序列化
JsonSerializer<LocalDateTime> jsonSerializer = (localDateTime, type, jsonSerializationContext)->new JsonPrimitive(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
//反序列化
JsonDeserializer<LocalDateTime> jsonDeserializer = (jsonElement, type, jsonDeserializationContext)->LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);

创建 GSON

Gson gson = new GsonBuilder().setPrettyPrinting()
        .registerTypeAdapter(LocalDateTime.class, jsonSerializer) //更改先后顺序没有影响
        .registerTypeAdapter(LocalDateTime.class, jsonDeserializer)
        .create();

参考

Java 8 LocalDateTime deserialized using Gson

Gson和LocalDateTime那点儿事

原文地址:https://www.cnblogs.com/hligy/p/13084757.html