zoukankan      html  css  js  c++  java
  • Gson 转换 Localdate 使用 GsonBuilder setDateFormat 无效

    setDateFormat(String pattern)方法
    决定序列化和反序列化 java.util.Date,java.sql.Timestamp,java.sql.Timestamp的格式

    并不支持localdata 所以需要手写一个 适配器来完成

    private Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd")
                .registerTypeAdapter(LocalDate.class,new LocalDataTypeAdapter())
                .create();
    package com.chinagoods.personnel.config;
    
    import com.google.gson.*;
    
    import java.lang.reflect.Type;
    import java.text.DateFormat;
    import java.text.SimpleDateFormat;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    
    /**
     * @Author: {---chenzhichao---}
     * @Date: 2020/6/2 20:04
     */
    public class LocalDataTypeAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {
        private final DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        @Override
        public LocalDate deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
            if (!(jsonElement instanceof JsonPrimitive)){
                throw new JsonParseException("The date should be a string value");
            }
            return null;
        }
    
        @Override
        public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
            DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            String createTime = dateTimeFormatter.format(localDate);
            return new JsonPrimitive(createTime);
        }
    }

  • 相关阅读:
    spring boot拦截器中获取request post请求中的参数
    netty与spring学习
    拦截器,过滤器,监听器
    CA 根证书不在“受信任的根证书颁发机构”存储区
    SpringBoot整合Shiro
    远程服务接口聚合带来的性能提升
    常见软件安全性漏洞及处理
    Mybatis中的CDATA标签
    idea运行固定多个模块项目
    理解Node.js事件驱动编程
  • 原文地址:https://www.cnblogs.com/kyousuke/p/13033598.html
Copyright © 2011-2022 走看看