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那点儿事

  • 相关阅读:
    如何彻底卸载Oracle11g
    Oracle 11g的安装
    python 循环队列的实现
    numpy模块学习笔记
    Python 进程之间共享数据
    python异步加协程获取比特币市场信息
    MySQL中, 如何查询某一天, 某一月, 某一年的数据.
    js获取时间
    nodejs爬虫笔记(五)---利用nightmare模拟点击下一页
    nodejs爬虫笔记(四)---利用nightmare解决加载更多问题
  • 原文地址:https://www.cnblogs.com/hligy/p/13084757.html
Copyright © 2011-2022 走看看