spring boot @ResponseBody轉換JSON 時 Date 類型處理方法

這裏一共有兩種不同解析方式(Jackson和FastJson兩種方式,springboot我用的1.x的版本)

第一種方式:默認的json處理是 jackson 也就是對configureMessageConverters 沒做配置時

  mybatis數據查詢返回的時間,是一串數字,如何轉化成時間。兩種方法,推薦第一種

  方法一:

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

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

  spring.jackson.time-zone=GMT+8

  方法二:

  @JsonFormat(timezone = “GMT+8”, pattern = “yyyyMMddHHmmss”)

  private Date createTime;

第二種方式:當configureMessageConverters 配置爲FasJson處理時;

  方法一:全局配置: fastJsonConfig.setDateFormat(“yyyy-MM-dd HH:mm:ss”);
  

@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;

說明:這裏如果字段和全局都配置了 ,最後是以全局轉換

文章來源

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章