SpringBoot总结

Posted kwdlh

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SpringBoot总结相关的知识,希望对你有一定的参考价值。

Jackson

将null转成""

@Configuration
public class JacksonConfig {

    @Bean
    @Primary
    @ConditionalOnMissingBean(ObjectMapper.class)
    public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder jackson2ObjectMapperBuilder){
        ObjectMapper objectMapper = jackson2ObjectMapperBuilder.createXmlMapper(false).build();
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator
            , SerializerProvider serializerProvider) throws IOException {
                jsonGenerator.writeString("");
            }
        });
        return objectMapper;
    }

}

FastJson

将null转成""

@Configuration
public class fastJsonConfig extends WebMvcConfigurationSupport {

/**
* 使用阿里 FastJson 作为JSON MessageConverter
* @param converters
*/
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>>
converters) {
      FastJsonHttpMessageConverter converter = new
      FastJsonHttpMessageConverter();
      FastJsonConfig config = new FastJsonConfig();
      config.setSerializerFeatures(
      // 保留map空的字段
      SerializerFeature.WriteMapNullValue,
      // 将String类型的null转成""
      SerializerFeature.WriteNullStringAsEmpty,
      // 将Number类型的null转成0
      SerializerFeature.WriteNullNumberAsZero,
      // 将List类型的null转成[]
      SerializerFeature.WriteNullListAsEmpty,
      // 将Boolean类型的null转成false
      SerializerFeature.WriteNullBooleanAsFalse,
      // 避免循环引用
      SerializerFeature.DisableCircularReferenceDetect);
      converter.setFastJsonConfig(config);
      converter.setDefaultCharset(Charset.forName("UTF-8"));
      List<MediaType> mediaTypeList = new ArrayList<>();
      // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces
      = "application/json"
      mediaTypeList.add(MediaType.APPLICATION_JSON);
      converter.setSupportedMediaTypes(mediaTypeList);
      converters.add(converter);
      }
}

以上是关于SpringBoot总结的主要内容,如果未能解决你的问题,请参考以下文章

python常用代码片段总结

BootStrap有用代码片段(持续总结)

SpringBoot中表单提交报错“Content type ‘application/x-www-form-urlencoded;charset=UTF-8‘ not supported“(代码片段

BootStrap实用代码片段(持续总结)

回归 | js实用代码片段的封装与总结(持续更新中...)

Spring boot:thymeleaf 没有正确渲染片段