spring boot 返回json數(shù)據(jù)時(shí)候日期格式化

方式一(配置文件方式):
注意: 使用配置文件方式的話,不能存在帶@EnableWebMvc注解的配置類,否則其作用會(huì)被屏蔽!!!
1、如果是application.properties配置文件,在文件中加入如下配置

spring.mvc.media-types.*=text/html;application/json
spring.jackson.date-format=yyyy-MM-dd HH:mm
spring.jackson.joda-date-time-format=yyyy-MM-dd HH:mm:ss

2、如果是application.yml配置文件,在文件中加入如下配置

spring: 
  jackson: 
    date-format: yyyy-MM-dd HH:mm:ss

方式二(配置類方式):
創(chuàng)建配置類WebConfig.java,注意不能缺少@EnableWebMvc和@Configuration注解以及代碼中兩個(gè)方法所引用的類要正確。

package com.beibei.doc.config;

import java.text.SimpleDateFormat;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * web相關(guān)
 * @author beibei
 *
 */
@EnableWebMvc
@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

//定義時(shí)間格式轉(zhuǎn)換器
@Bean
public MappingJackson2HttpMessageConverter jackson2HttpMessageConverter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    converter.setObjectMapper(mapper);
    return converter;
}

//添加轉(zhuǎn)換器
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    //將我們定義的時(shí)間格式轉(zhuǎn)換器添加到轉(zhuǎn)換器列表中,
    //這樣jackson格式化時(shí)候但凡遇到Date類型就會(huì)轉(zhuǎn)換成我們定義的格式
    converters.add(jackson2HttpMessageConverter());
}
}

如果上面兩種方式配置同時(shí)存在,只有第二種會(huì)起作用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

推薦閱讀更多精彩內(nèi)容