SpringBoot总结

2021-03-20 21:27

阅读:535

标签:number   condition   rri   cat   引用   get   port   public   ast   

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() {
            @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>
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 mediaTypeList = new ArrayList();
      // 解决中文乱码问题,相当于在Controller上的@RequestMapping中加了个属性produces
      = "application/json"
      mediaTypeList.add(MediaType.APPLICATION_JSON);
      converter.setSupportedMediaTypes(mediaTypeList);
      converters.add(converter);
      }
}

SpringBoot总结

标签:number   condition   rri   cat   引用   get   port   public   ast   

原文地址:https://www.cnblogs.com/kwdlh/p/13910218.html


评论


亲,登录后才可以留言!