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


    springboot 版本 2.7.3

    1、依赖导入

     		<dependency>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-starter-webartifactId>
            dependency>
    
            <dependency>
                <groupId>org.projectlombokgroupId>
                <artifactId>lombokartifactId>
                <optional>trueoptional>
            dependency>
            <dependency>
                <groupId>com.google.code.gsongroupId>
                <artifactId>gsonartifactId>
            dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

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

    2、application.yaml配置

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

    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 {
        //
        //     @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 {
        //
        //     @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"));
                }
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82

    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;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    @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;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    curl 127.0.0.1:8080/book                  
    {"id":"1","name":"tcoding","publishDate":"2022-09-10","createTime":"2022-09-10 15:32:17"}% 
    
    • 1
    • 2
     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"}%   
    
    
    • 1
    • 2
    • 3

    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();
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    是为了注入到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

  • 相关阅读:
    【数学思维】运筹学-线性规划之标准形式与Hidden LP
    GO -mod和​GO111MODULE设置的那些事原创
    Mysql 查询人数大于或等于 100 且 id 连续的三行或更多行记录。
    linux安装node(含npm命令) 并配置淘宝镜像源
    2. MongoDB 应用与开发
    Rollup:zkSync v2.0和ZK-Rollup的未来
    MATLAB 机械臂逆运动学进行轨迹控制建模
    Redis事务管理
    使用Docker搭建自己的Bitwarden密码管理服务
    Oracle 19C 静默安装 GoldenGate
  • 原文地址:https://blog.csdn.net/qq_23934475/article/details/126796526