目录
一、使用场景
二、环境准备
1、引入依赖
2、实体类
三、示例
1、不返回空值
(1)方式
(2)测试
(3)说明
2、不返回部分属性
(1)方式
(2)测试
一、使用场景
在开发过程中,有时候需要将后端数据返回前端,此时有些数据为空属性不需要返回,或者有些属性不需要返回,因此就需要处理。
二、环境准备
1、引入依赖
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-core</artifactId><version>2.10.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-annotations</artifactId><version>2.10.0</version></dependency><dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.10.0</version></dependency>
2、实体类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student{private Integer id;private String name;private Integer age;private String address;private BigDecimal score;private String className;private List<String> subjectList = new ArrayList<>();}
三、示例
1、不返回空值
(1)方式
在实体类上面加上下面的注解:
@JsonInclude(JsonInclude.Include.NON_EMPTY)
(2)测试
Controller里面的方法:
@PostMapping("/getData")public R getData(){Student student = new Student();student.setName("Tom");student.setAge(22);return R.ok().data("student", student);}
测试结果:
(3)说明
如果要对部分属性进行空值限制,分为两类:
- 字符串、基本数据类型的设置,使用JsonInclude.Include.NON_NULL
- 对象、数组之类的设置,使用JsonInclude.Include.NON_EMPTY
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;@Data
@NoArgsConstructor
@AllArgsConstructor
public class Student{@JsonInclude(JsonInclude.Include.NON_NULL)private Integer id;@JsonInclude(JsonInclude.Include.NON_NULL)private String name;@JsonInclude(JsonInclude.Include.NON_NULL)private Integer age;@JsonInclude(JsonInclude.Include.NON_NULL)private String address;@JsonInclude(JsonInclude.Include.NON_NULL)private BigDecimal score;@JsonInclude(JsonInclude.Include.NON_NULL)private String className;@JsonInclude(JsonInclude.Include.NON_EMPTY)private List<String> subjectList = new ArrayList<>();}
2、不返回部分属性
(1)方式
实体类属性上使用注解:
@JsonIgnore
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;@Data
@NoArgsConstructor
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Student {private Integer id;private String name;private Integer age;@JsonIgnoreprivate String address;private BigDecimal score;private String className;private List<String> subjectList = new ArrayList<>();}
(2)测试
Controller里面的方法:
@PostMapping("/getData")public R getData(){Student student = new Student();student.setId(1001);student.setName("Tom");student.setAge(22);student.setAddress("浙江");return R.ok().data("student", student);}
测试结果: