1. 程式人生 > >Springboot統一配置Jackson(全域性命名轉換)

Springboot統一配置Jackson(全域性命名轉換)

 

 

Springboot統一配置Jackson - Ryan.Miao - 部落格園
https://www.cnblogs.com/woshimrf/p/springboot-jackson-global-config.html

 

Jackson命名轉換 - liuguidongliuguidong的專欄 - CSDN部落格
https://blog.csdn.net/liuguidongliuguidong/article/details/72968226

 

/////////////////////////////////

 

Jackson命名轉換
jackson在java物件與json欄位之間的轉換,提供三種預設的轉換規則, 
即繼承自PropertyNamingStrategyBase的類有三個

PascalCaseStrategy:首字母變為大寫

LowerCaseWithUnderscoresStrategy:小寫字母+下劃線,java物件屬性名的大寫字母會轉換成小寫字母+下劃線的形式 (已經廢棄, 用SnakeCaseStrategy代替)

LowerCaseStrategy:小寫字母的形式

如果要定義自己的轉換規則,可以繼承PropertyNamingStrategyBase抽象類並重寫方法translate; 
如下

// 自定義轉換規則MyCustomNamingConfig

public class MyCustomNamingConfig extends PropertyNamingStrategyBase{
    @Override
    public String translate(String propertyName) {
        return propertyName;
    }
}



然後在要轉換成json的類上加@JsonNaming(MyCustomNamingConfig.class)

//  這裡使用自定義轉換規則MyCustomNamingConfig, 也可以使用Jackson內建規則PropertyNamingStrategy.SnakeCaseStrategy::class, PropertyNamingStrategy.PascalCaseStrategy::class等
@JsonNaming(MyCustomNamingConfig.class)  
@Data
class JackSonObj{
    private testId;
    private testName;
}

效果: 

對於spring boot來說, 則該物件在作為響應時, 預設進行命名規則轉換

 

 

 

 

 

 

////////////////////////////////////////////////////////////////////

//////////////////////////如果想全域性配置Jackson的命名轉換, 可以配置spring boot, 請看下文//////////////////////////////////////////

////////////////////////////////////////////////////////////////////

 

 

 

 

 

經常要為介面響應物件設定屬性,序列化的時候是不是包含空值,反序列化的時候是否忽略不認識的欄位。所以,必須要手動制定ObjectMapper或者在類上宣告

@JsonInclude(Include.NON_NULL)
@JsonIgnoreProperties(ignoreUnknown = true)

雖然不算複雜,但既然統一了規則,那就來個統一設定吧。

在springboo1.5+以上的版本可以這麼設定Jackson的一些屬性配置, 可以關注property-naming-strategy命名風格配置

spring:
  jackson:
    serialization:
      WRITE_DATES_AS_TIMESTAMPS: false
    default-property-inclusion: non_null    # 轉換物件時過濾掉null值
    property-naming-strategy: SNAKE_CASE  # 出參時所有屬性自動轉下劃線風格

更多配置參見 org.springframework.boot.autoconfigure.jackson.JacksonProperties檔案


@ConfigurationProperties(
    prefix = "spring.jackson"
)
public class JacksonProperties {
    private String dateFormat;
    private String jodaDateTimeFormat;
    private String propertyNamingStrategy;
    private Map<SerializationFeature, Boolean> serialization = new HashMap();
    private Map<DeserializationFeature, Boolean> deserialization = new HashMap();
    private Map<MapperFeature, Boolean> mapper = new HashMap();
    private Map<Feature, Boolean> parser = new HashMap();
    private Map<com.fasterxml.jackson.core.JsonGenerator.Feature, Boolean> generator = new HashMap();
    private Include defaultPropertyInclusion;
    private TimeZone timeZone = null;
    private Locale locale;
    
    //省略
}