1、前言
在实际的项目中,我们从数据库查出的数据并不是所有的字段要返回到前台,但是一般都是统一的实体,这个时候,就需要过滤一些不需要返回的对象属性。
2、实现
2.1、@JsonIgnore
在实体中字段添加@JsonIgnore可以注释不需要的字段;
@JsonIgnore注解用来忽略某些字段,可以用在变量或者Getter方法上,用在Setter方法时,和变量效果一样。这个注解一般用在我们要忽略的字段上
@Data
@EqualsAndHashCode(callSuper = false)
public class Test implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String age;
@JsonIgnore
private String subName;
}
@GetMapping("test")
public Test test(Test test) {
return test;
}
2.2、@JsonIgnoreProperties
@JsonIgnoreProperties
@JsonIgnoreProperties(ignoreUnknown = true),将这个注解写在类上之后,就会忽略类中不存在的字段。这个注解还可以指定要忽略的字段,例如@JsonIgnoreProperties({ “password”, “secretKey” })
@Data
@EqualsAndHashCode(callSuper = false)
@JsonIgnoreProperties(value = {"subName", "age"})
public class Test implements Serializable {
private static final long serialVersionUID=1L;
@TableId(value = "id", type = IdType.AUTO)
private Integer id;
private String name;
private String age;
private String subName;
}

本文是Spring Boot教学系列的一部分,主要讲解如何在后端过滤返回给前端的JSON对象属性。通过使用@JsonIgnore、@JsonIgnoreProperties、@JsonView以及自定义过滤方法来实现这一目标。文中探讨了各种方法的优缺点,例如@JsonIgnoreProperties的便捷性,@JsonView在特定场景下的适用性,以及自定义过滤方法的灵活性问题。
4154

被折叠的 条评论
为什么被折叠?



