修改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);
}
}
相關文章
相關標籤/搜索