zoukankan      html  css  js  c++  java
  • 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那点儿事

  • 相关阅读:
    exp迁移测试库10.2.0.5
    DG_Check检测
    DG Switch over
    CPU查询
    记录数据库中,段大小的数据增长情况
    C++ 多态
    java反射
    git的基本概念
    实现MySQL的Replication
    网页只允许中国用户访问
  • 原文地址:https://www.cnblogs.com/hligy/p/13084757.html
Copyright © 2011-2022 走看看