1. 程式人生 > >Spring Boot @ResponseBody 轉換 JSON資料時Date 型別處理方法

Spring Boot @ResponseBody 轉換 JSON資料時Date 型別處理方法

引用處:

https://blog.csdn.net/molashaonian/article/details/53025118
https://blog.csdn.net/henianyou/article/details/81945409

 

  • 解析JSON的方式:

這裡一共有兩種不同解析方式 Jackson FastJson兩種方式

  • Jackson的方式:SpringBoot 預設的json處理是 jackson 也就是對configureMessageConverters 沒做配置;

全域性配置:

可以在apllication.property加入下面配置就可以了

  #時間戳統一轉換 
  spring.jackson.date-format=yyyy-MM-dd HH:mm:ss

    #時區指定

  spring.jackson.time-zone=GMT+8

區域性配置:

    可以在指定屬性的get方法上加註解的方式

(注意:如果在屬性上加,那麼會出現響應結果包含該屬性大寫,小寫兩個欄位,如:Result:{Ao:xxx,ao:xxx} )

@JsonFormat(timezone = “GMT+8”, pattern = “yyyyMMddHHmmss”)
@JsonProperty("Date")  //用來指定該屬性的json序列化欄位名,比如:不進行首字母小寫轉換
public Date getDate() {
    return Date;
}

 

  • FastJson的方式:需要更改configureMessageConverters 配置為FasJson

全域性配置:

//mvc config 配置類
@Configuration
public class WebMvcConfig extends WebMvcConfigurerAdapter {

//修改預設轉換的配置
@Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);

        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();

        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteNullStringAsEmpty
        );

       //此處是全域性處理方式
        fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");

        fastConverter.setFastJsonConfig(fastJsonConfig);

        List<MediaType> supportedMediaTypes = new ArrayList<MediaType>();
        supportedMediaTypes.add(MediaType.ALL); // 全部格式
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        converters.add(fastConverter);
    }   
}

區域性配置:

@JSONField(format=”yyyyMMdd”)

 private Date createTime;

//如果也出現json響應欄位多的問題,那麼也加在get方法上

說明:這裡如果欄位的區域性配置和全域性都配置了 ,那麼最後是以全域性轉換來的。