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

  • 相关阅读:
    Android 学习笔记5程序开发模式&拨号器&短信发送器小例程
    Android学习笔记6日志输出&单元测试
    utkernel 移植时调试方法
    在eclipse中查看Android SDK源代码
    (转载)怎样改进数据库的查询性能?
    asp.net 编程模型
    数据回传
    在博客园记录我的成长
    LeetCode14.最长公共前缀
    LeetCode206.反转链表
  • 原文地址:https://www.cnblogs.com/kyousuke/p/13033598.html
Copyright © 2011-2022 走看看