一、Jackson方式实现对null字段转为空字符串(springboot自带jackson)
springboot自带jackson,所以不需要额外引入坐标:
编写配置类:我的理解是实例化ObjectMapper对象交由spring管理,之后在使用jackson转化json字符串时执行
@Configuration public class JacksonConfig { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.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方式实现
需要手动引入依赖fastjson:
<dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.35</version> </dependency>
编写配置类:较完整的配置
该种方式是实现springmvc中的WebMvcConfigurationSupport类重新其中的configureMessageConverters方法,添加一个转换器来对返回值内容进行转换。 @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); } }
测试
上面两种方案都可行
我们编写两个类来进行测试:
@Data @AllArgsConstructor @NoArgsConstructor public class User { private Long id; private String name; private Integer age; private String email; private String address; } @RestController @RequestMapping("/api/v1/test") @Slf4j //在类上添加该接口 public class UserController { @GetMapping("/{id}") public ResultBody test(@PathVariable(value = "id")Integer myid){ ArrayList<User> users = new ArrayList<>(10); users.add(new User((long)111, "changlu", 11, null,null)); users.add(new User((long)111, null, 11, null,null)); users.add(new User((long)111, "changlu", 11, null,null)); users.add(new User((long)111, null, 11, null,null)); users.add(new User((long)111, "changlu", 11, null,null)); users.add(new User((long)111, null, 11, null,null)); users.add(new User((long)111, "changlu", 11, null,null)); return ResultBody.success(users); } }
转换成功!