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);
	  }  
}

你可能感兴趣的:(json)