jackson.date-format等配置不生效的問題


 描述

springboot項目中出參為json時,日期格式化配置一般為

spring.jackson.time-zone=GMT+8
spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

但是不生效,返回的是依舊是時間戳格式;

 

版本

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.1.RELEASE</version>
</parent>
            

 

 

原因

添加攔截器並繼承 WebMvcConfigurationSupport 后會覆蓋@EnableAutoConfiguration關於WebMvcAutoConfiguration的配置!從而導致所有的Date返回都變成時間戳。

https://www.cnblogs.com/sufferingStriver/p/9026764.html

 

解決

 1 package com.sitech.pgcenter.config;
 2  
 3 import com.fasterxml.jackson.databind.DeserializationFeature;
 4 import com.fasterxml.jackson.databind.ObjectMapper;
 5 import com.fasterxml.jackson.databind.module.SimpleModule;
 6 import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
 7 import org.springframework.context.annotation.Configuration;
 8 import org.springframework.http.converter.HttpMessageConverter;
 9 import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
10 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
11  
12 import java.text.SimpleDateFormat;
13 import java.util.List;
14  
15 /**
16  * @Description 解決springboot高版本下日期轉json時jackson方式不生效問題
17  *
18  */
19 @Configuration
20 public class DateFormatForJson implements WebMvcConfigurer {
21     /**
22      * 使用此方法, 以下 spring-boot: jackson時間格式化 配置 將會失效
23      * spring.jackson.time-zone=GMT+8
24      * spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
25      * 原因: 會覆蓋 @EnableAutoConfiguration 關於 WebMvcAutoConfiguration 的配置
26      * */
27     @Override
28     public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
29         MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
30         ObjectMapper objectMapper = converter.getObjectMapper();
31         // 生成JSON時,將所有Long轉換成String
32         SimpleModule simpleModule = new SimpleModule();
33         simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
34         simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
35         objectMapper.registerModule(simpleModule);
36         // 時間格式化
37         objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
38         objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
39         // 設置格式化內容
40         converter.setObjectMapper(objectMapper);
41         converters.add(0, converter);
42     }
43  
44 }

 

jackson的推薦配注釋說明:

spring: 
  jackson: 
    # 設置屬性命名策略,對應jackson下PropertyNamingStrategy中的常量值,SNAKE_CASE-返回的json駝峰式轉下划線,json body下划線傳到后端自動轉駝峰式 
    property-naming-strategy: SNAKE_CASE
    
    # 全局設置@JsonFormat的格式pattern 
    date-format: yyyy-MM-dd HH:mm:ss 
    
    # 當地時區 
    locale: zh 
    
    # 設置全局時區 
    time-zone: GMT+8 
    
    # 常用,全局設置pojo或被@JsonInclude注解的屬性的序列化方式 
    default-property-inclusion: NON_NULL #不為空的屬性才會序列化,具體屬性可看JsonInclude.Include 
    
    # 常規默認,枚舉類SerializationFeature中的枚舉屬性為key,值為boolean設置jackson序列化特性,具體key請看SerializationFeature源碼 
    serialization: 
      WRITE_DATES_AS_TIMESTAMPS: true # 返回的java.util.date轉換成timestamp 
      FAIL_ON_EMPTY_BEANS: true # 對象為空時是否報錯,默認true 
    
    # 枚舉類DeserializationFeature中的枚舉屬性為key,值為boolean設置jackson反序列化特性,具體key請看DeserializationFeature源碼 
    deserialization: 
      # 常用,json中含pojo不存在屬性時是否失敗報錯,默認true 
      FAIL_ON_UNKNOWN_PROPERTIES: false 
    
    # 枚舉類MapperFeature中的枚舉屬性為key,值為boolean設置jackson ObjectMapper特性 
    # ObjectMapper在jackson中負責json的讀寫、json與pojo的互轉、json tree的互轉,具體特性請看MapperFeature,常規默認即可 
    mapper: 
      # 使用getter取代setter探測屬性,如類中含getName()但不包含name屬性與setName(),傳輸的vo json格式模板中依舊含name屬性 
      USE_GETTERS_AS_SETTERS: true #默認false
    
    # 枚舉類JsonParser.Feature枚舉類中的枚舉屬性為key,值為boolean設置jackson JsonParser特性 
    # JsonParser在jackson中負責json內容的讀取,具體特性請看JsonParser.Feature,一般無需設置默認即可 
    parser: 
      ALLOW_SINGLE_QUOTES: true # 是否允許出現單引號,默認false 
    
    # 枚舉類JsonGenerator.Feature枚舉類中的枚舉屬性為key,值為boolean設置jackson JsonGenerator特性,一般無需設置默認即可 
    # JsonGenerator在jackson中負責編寫json內容,具體特性請看JsonGenerator.Feature

 

使用配置spring.jackson.property-naming-strategy=SNAKE_CASE

SNAKE_CASE-返回的json駝峰式轉下划線,json body下划線傳到后端自動轉駝峰式 

但是,很不幸,由於項目中使用了WebMvcConfigurationSupport,導致jackson配置失效

 

於是乎,尋找其他解決方法,一種方式是在類上面加

@JsonNaming(PropertyNamingStrategy.SnakeCaseStrategy.class)

 

也可以在字段上加(這種方式不建議,每個字段上都加,任務量太大)

@JsonProperty(value = "detail_address")

 

另一種方式,重寫WebMvcConfigurationSupport類的extendMessageConverters方法

   /**
     * 使用此方法, 以下 spring-boot: jackson時間格式化 配置 將會失效
     * spring.jackson.time-zone=GMT+8
     * spring.jackson.date-format=yyyy-MM-dd HH:mm:ss
     * 原因: 會覆蓋 @EnableAutoConfiguration 關於 WebMvcAutoConfiguration 的配置
     * */
    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = converter.getObjectMapper();
        
        // 設置駝峰標志轉下划線
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
        
        // 設置格式化內容
        converter.setObjectMapper(objectMapper);
        converters.add(0, converter);
    }

 

代碼示例:https://github.com/yucong/spring-boot-learning/tree/master/chapter-31-jackson

 

擴展補充:

springboot自定義消息轉換器HttpMessageConverter
https://www.cnblogs.com/hhhshct/p/9676604.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM