我们在Controller中如果传递的参数为对象的话,此时我们传递过来的Json串是使用SpringBoot的默认解析器来进行解析的,但是JackSon的体验并不是很好,我们可以修改成阿里的FastJson来获取更好的体验。例如
@PostMapping("/users-anon/test")
public Test save(@RequestBody Test test) {
testRepository.save(test);
return test;
}
此时我们需要设置一个配置类,就可以达到该目的
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setCharset(Charset.forName("UTF-8"));
config.setDateFormat("yyyyMMdd HH:mm:ssS");
//设置允许返回为null的属性
config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
fastJsonConverter.setFastJsonConfig(config);
List<MediaType> list = new ArrayList<>();
list.add(MediaType.APPLICATION_JSON_UTF8);
fastJsonConverter.setSupportedMediaTypes(list);
converters.add(fastJsonConverter);
}
}