zoukankan      html  css  js  c++  java
  • JSON Gson的LocalDateTime和String转化

    package com.bitsun.bizcenter.ic.api.config;
    
    import com.google.gson.*;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    
    import java.time.LocalDate;
    import java.time.LocalDateTime;
    import java.time.format.DateTimeFormatter;
    
    /**
     * @author leizige
     */
    @Configuration
    public class GSONConfiguration {
    
        //序列化
        final static JsonSerializer<LocalDateTime> jsonSerializerDateTime = (localDateTime, type, jsonSerializationContext) -> new JsonPrimitive(localDateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME));
        final static JsonSerializer<LocalDate> jsonSerializerDate = (localDate, type, jsonSerializationContext) -> new JsonPrimitive(localDate.format(DateTimeFormatter.ISO_LOCAL_DATE));
        //反序列化
        final static JsonDeserializer<LocalDateTime> jsonDeserializerDateTime = (jsonElement, type, jsonDeserializationContext) -> LocalDateTime.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ISO_LOCAL_DATE_TIME);
        final static JsonDeserializer<LocalDate> jsonDeserializerDate = (jsonElement, type, jsonDeserializationContext) -> LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(), DateTimeFormatter.ISO_LOCAL_DATE);
    
        @Bean
        public Gson create() {
            return new GsonBuilder()
                    .setPrettyPrinting()
                    /* 更改先后顺序没有影响 */
                    .registerTypeAdapter(LocalDateTime.class, jsonSerializerDateTime)
                    .registerTypeAdapter(LocalDate.class, jsonSerializerDate)
                    .registerTypeAdapter(LocalDateTime.class, jsonDeserializerDateTime)
                    .registerTypeAdapter(LocalDate.class, jsonDeserializerDate)
                    .create();
        }
    }
    
  • 相关阅读:
    在vue项目中stylus的安装及使用
    如何在vue中全局引入stylus文件的公共变量
    d3.js在vue项目中的安装及案例
    cytoscape.js在vue项目中的安装及案例
    vue路由router的三种传参方式
    vue项目警告There are multiple modules with names that only differ in casing
    vue+iview实现一行平均五列布局
    JVM 内存对象管理
    JVM 垃圾回收机制
    面试随笔-01
  • 原文地址:https://www.cnblogs.com/leizzige/p/13367286.html
Copyright © 2011-2022 走看看