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

  • 相关阅读:
    多项式求逆
    luoguP3380 【模板】二逼平衡树(树套树)
    NTT
    poj2728 Desert King
    eclipse使用
    Java之面向对象
    Python实现终端高亮显示
    requests
    Go基础
    0919CSP-S模拟测试赛后总结
  • 原文地址:https://www.cnblogs.com/kyousuke/p/13033598.html
Copyright © 2011-2022 走看看