一、需求背景
在实际开发过程中,通过接口查询得到的json数据可能会包含null,null数据是无意义的,可能导致接收方未知的报错(比如:一些老的系统可能拿json去转xml格式),那么如何解决接口返回null值问题呢?
Java接口返回json如何去除为null的数据?
在Java中,使用Jackson或者Gson等库可以很容易地将对象转换成JSON格式。如果你想要在生成JSON时自动忽略为null的字段,可以在使用这些库时进行配置。
二、实现方案
2.1 作用在指定的类上
对于Jackson,可以使用@JsonInclude(JsonInclude.Include.NON_NULL)注解在类级别上
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RegisterAddress {
private String id;
private String prov;
private String city;
private String country;
}
2.2 在yml中做全局配置
在Spring Boot应用中,可以在application.properties或application.yml中添加以下配置:
application.properties
spring.jackson.default-property-inclusion=non_null
application.yml
spring:
jackson:
default-property-inclusion: non_null
2.3 定义全局配置类
package com.saferycom.nonull;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @author LH
*/
@Configuration
public class JacksonConfig {
@Bean
public ObjectMapper objectMapper() {
ObjectMapper mapper = new ObjectMapper();
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
return mapper;
}
}
上述,三种解决方式任选其一,第一种适用于特定的类上,无法实现全局配置;第二、三种方法可以实现全局配置,根据项目实际需要,任选其一即可。