当前位置: 首页 > news >正文

SpringBoot MVC使用Gson,序列化LocalDate,LocalDateTime

springboot 版本 2.7.3

1、依赖导入

 		<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
        </dependency>

因为springBoot做了jar包版本管理,所以不需要引入version标签

2、application.yaml配置

spring.mvc.converters.preferred-json-mapper: gson

3、GsonConfig

@Configuration
public class GsonConfig {

    /**
     * 自定义gson配置
     */
    @Bean
    public GsonBuilderCustomizer customizer() {
        return b -> b
            .setLongSerializationPolicy(LongSerializationPolicy.STRING)
            .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
            .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
            // The date format will be used to serialize and deserialize Date and in case the java.sql module is present, also java.sql
            // .Timestamp and java.sql.Date.
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .serializeNulls()
            .create();
    }

    /**
     * 只有序列化功能
     */
    // public static class LocalDateTimeSerializer implements JsonSerializer<LocalDateTime> {
    //
    //     @Override
    //     public JsonElement serialize(LocalDateTime localDateTime, Type type, JsonSerializationContext jsonSerializationContext) {
    //         return new JsonPrimitive(localDateTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
    //     }
    // }
    //
    // public static class LocalDateSerializer implements JsonSerializer<LocalDate> {
    //
    //     @Override
    //     public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) {
    //         return new JsonPrimitive(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
    //     }
    // }

    public static class LocalDateAdapter extends TypeAdapter<LocalDate> {

        @Override
        public void write(final JsonWriter jsonWriter, final LocalDate localDate) throws IOException {
            if (localDate == null) {
                jsonWriter.nullValue();
            } else {
                jsonWriter.value(localDate.toString());
            }
        }

        @Override
        public LocalDate read(final JsonReader jsonReader) throws IOException {
            if (jsonReader.peek() == JsonToken.NULL) {
                jsonReader.nextNull();
                return null;
            } else {
                return LocalDate.parse(jsonReader.nextString());
            }
        }
    }

    public static class LocalDateTimeAdapter extends TypeAdapter<LocalDateTime> {

        @Override
        public void write(final JsonWriter jsonWriter, final LocalDateTime localDate) throws IOException {
            if (localDate == null) {
                jsonWriter.nullValue();
            } else {
                jsonWriter.value(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            }
        }

        @Override
        public LocalDateTime read(final JsonReader jsonReader) throws IOException {
            if (jsonReader.peek() == JsonToken.NULL) {
                jsonReader.nextNull();
                return null;
            } else {
                return LocalDateTime.parse(jsonReader.nextString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
        }
    }
}

4、测试

@Data
public class Book {

    private Long id;
    private String name;

    //@JsonAdapter(value = GsonConfig.LocalDateAdapter.class)
    private LocalDate publishDate;
   //@JsonAdapter(value = GsonConfig.LocalDateTimeAdapter.class)
    private LocalDateTime createTime;
}
@RestController
@RequestMapping("/book")
public class IndexController {

    @PostMapping
    public Book save(@RequestBody Book book) {
        return book;
    }

    @GetMapping
    public Book get() {
        Book book = new Book();
        book.setId(1L);
        book.setName("tcoding");
        book.setCreateTime(LocalDateTime.now());
        book.setPublishDate(LocalDate.now());
        return book;
    }
}
curl 127.0.0.1:8080/book                  
{"id":"1","name":"tcoding","publishDate":"2022-09-10","createTime":"2022-09-10 15:32:17"}% 
 curl -X POST 127.0.0.1:8080/book --header 'Content-Type: application/json'    --data-raw '{"id":"1","name":"tcoding","publishDate":"2022-09-10","createTime":"2022-09-10 15:32:17"}'                              
{"id":"1","name":"tcoding","publishDate":"2022-09-10","createTime":"2022-09-10 15:32:17"}%   

5、 SpringBoot Gson自动配置流程

GsonAutoConfiguration

在这里插入图片描述

上面GsonConfig配置类里面

  @Bean
    public GsonBuilderCustomizer customizer() {
        return b -> b
            .setLongSerializationPolicy(LongSerializationPolicy.STRING)
            .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
            .registerTypeAdapter(LocalDateTime.class, new LocalDateTimeAdapter())
            // The date format will be used to serialize and deserialize Date and in case the java.sql module is present, also java.sql
            // .Timestamp and java.sql.Date.
            .setDateFormat("yyyy-MM-dd HH:mm:ss")
            .serializeNulls()
            .create();
    }

是为了注入到GsonBuilder

根据 GsonBuilder生成Gson

GsonHttpMessageConvertersConfiguration

在这里插入图片描述
在这里插入图片描述
yaml配置 spring.mvc.converters.preferred-json-mapper的值为gson
则自动生成 GsonHttpMessageConverter bean

HttpMessageConvertersAutoConfiguration

在这里插入图片描述

WebMvcAutoConfigurationAdapter

在这里插入图片描述

源码地址 https://github.com/googalAmbition/hello-spring-boot/tree/main/31-gson

相关文章:

  • 戴尔G3-3579改固态散热
  • C3P0和Druid数据库连接池的使用
  • 2022中国消费者智能网联汽车数据安全和个人隐私意识与顾虑调查报告
  • Java 大文件分片上传
  • Redis未授权访问漏洞
  • Java 修饰符 private、default、protected、public 的应用实例 (方法)
  • Java 多线程:锁(一)
  • VMware 搭建linux操作系统,入门必看
  • 2022牛客多校(三)
  • 阿里云服务器和腾讯云服务器哪个更好?多维度对比得出了结论
  • sqli-labs(less-1)
  • 【Ubuntu】gcc与Makefile操作
  • Python零基础入门篇 · 21】:构造函数、类属性和实例属性的访问
  • Invalid bound statement (not found)出现的原因和解决方法
  • hive笔记八:自定义函数-自定义UDF函数/自定义UDTF函数
  • @angular/forms 源码解析之双向绑定
  • 30天自制操作系统-2
  • Apache Spark Streaming 使用实例
  • JavaWeb(学习笔记二)
  • JAVA之继承和多态
  • js正则,这点儿就够用了
  • Mysql5.6主从复制
  • PHP变量
  • redis学习笔记(三):列表、集合、有序集合
  • scala基础语法(二)
  • 阿里云购买磁盘后挂载
  • 给初学者:JavaScript 中数组操作注意点
  • 扫描识别控件Dynamic Web TWAIN v12.2发布,改进SSL证书
  • 使用API自动生成工具优化前端工作流
  • 网络应用优化——时延与带宽
  • 异常机制详解
  • - 语言经验 - 《c++的高性能内存管理库tcmalloc和jemalloc》
  • 原生js练习题---第五课
  • 责任链模式的两种实现
  • 智能合约开发环境搭建及Hello World合约
  • 《TCP IP 详解卷1:协议》阅读笔记 - 第六章
  • #{}和${}的区别?
  • #我与Java虚拟机的故事#连载03:面试过的百度,滴滴,快手都问了这些问题
  • $refs 、$nextTic、动态组件、name的使用
  • (4)通过调用hadoop的java api实现本地文件上传到hadoop文件系统上
  • (MATLAB)第五章-矩阵运算
  • (六)什么是Vite——热更新时vite、webpack做了什么
  • (万字长文)Spring的核心知识尽揽其中
  • (五)IO流之ByteArrayInput/OutputStream
  • .\OBJ\test1.axf: Error: L6230W: Ignoring --entry command. Cannot find argumen 'Reset_Handler'
  • .NET Core WebAPI中使用swagger版本控制,添加注释
  • .net oracle 连接超时_Mysql连接数据库异常汇总【必收藏】
  • .NET框架类在ASP.NET中的使用(2) ——QA
  • .NET中 MVC 工厂模式浅析
  • [2016.7 test.5] T1
  • [Ariticle] 厚黑之道 一 小狐狸听故事
  • [bzoj1901]: Zju2112 Dynamic Rankings
  • [C#]使用DlibDotNet人脸检测人脸68特征点识别人脸5特征点识别人脸对齐人脸比对FaceMesh
  • [c++] 什么是平凡类型,标准布局类型,POD类型,聚合体
  • [C++从入门到精通] 14.虚函数、纯虚函数和虚析构(virtual)