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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

tcoding

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值