修改Springboot 2的默认Json解析器JackSon为FastJson

咱们在Controller中若是传递的参数为对象的话,此时咱们传递过来的Json串是使用SpringBoot的默认解析器来进行解析的,可是JackSon的体验并非很好,咱们能够修改为阿里的FastJson来获取更好的体验。例如java

@PostMapping("/users-anon/test")
public Test save(@RequestBody Test test) {
    testRepository.save(test);
    return test;
}

此时咱们须要设置一个配置类,就能够达到该目的app

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

若是在项目中使用了java 8的日期类型(LocalDate,LocalDateTime),建议不要限制日期格式,不然会报错。ide

@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("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
//        config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
        fastJsonConverter.setFastJsonConfig(config);
        List<MediaType> list = new ArrayList<>();
        list.add(MediaType.APPLICATION_JSON_UTF8);
        fastJsonConverter.setSupportedMediaTypes(list);
        converters.add(fastJsonConverter);
}
}
相关文章
相关标签/搜索