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);
        }
    }

  • 相关阅读:
    Redis-命令-脚本
    Redis-命令-事务
    Redis-命令-发布订阅
    Redis-命令-HyperLogLog
    Redis-命令-有序集合(sorted set)
    Redis-命令-集合(Set)
    Redis-命令-列表(List)
    Python实例浅谈之三Python与C/C++相互调用
    python调用(运行)外部程序
    Sublime Text3 配置设置攻略
  • 原文地址:https://www.cnblogs.com/kyousuke/p/13033598.html
Copyright © 2011-2022 走看看