1. 程式人生 > >SpringBoot開發REST API,資料格式化全域性配置

SpringBoot開發REST API,資料格式化全域性配置

開發REST API時,通常需要對日期等資料型別進行格式化,以FastJson為例,可以使用@JSONField註解對需要格式化的欄位進行配置,也可以使用如下的全域性配置類

配置類

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import com.alibaba.fastjson.serializer.SerializerFeature; import com.alibaba.fastjson.support.config.FastJsonConfig; import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter; /** * WebMvcConfig * @author: Iffie * @date: 2018年9月27日 */
@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); } }