使用场景

在项目中,后端查询数据库返回的字段需要过滤传给前端,或者只需要一部分字段

方法一    new

newVO,DTO类,实体类来解决  (太老土的做法)

 

方法二   使用transient关键字  (密码,和身份证号字段多使用)   

把需要过滤掉字段使用transient关键字修饰,这样在调用JSON的toString方法时,被transient修饰的字段不会出现在最终的json字符串中

例子:   private transient String id;      (在多个接口中使用这个字段 ,如果不是都要过滤这个字段时候, 就不适合使用)

 

方法三   使用注解@JSONField(serialize=false)   作用和使用情况同方法二

例子: @JSONField(serialize=false) 

    private String id;

 

方法四  使用fastjson属性过滤器SimplePropertyPreFilter    (推荐使用 更灵活)

           SimplePropertyPreFilter实现了PropertyPreFilter 

fastjson过滤掉不需要返回的字段

 

例子:  Student 相当于VO,DTO类或者实体类

fastjson过滤掉不需要返回的字段

要输出字段为空的情况  增加一个参数 SerializerFeature.WriteMapNullValue

fastjson过滤掉不需要返回的字段

 

 

public class Student {

    /** 学号 */
    private long id;

    private String name;

    private int age;

    /** 年级 */
    private int grade;

    /** 专业 */
    private String major;

    /** 学校 */
    private String school;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getGrade() {
        return grade;
    }

    public void setGrade(int grade) {
        this.grade = grade;
    }

    public String getMajor() {
        return major;
    }

    public void setMajor(String major) {
        this.major = major;
    }

    public String getSchool() {
        return school;
    }

    public void setSchool(String school) {
        this.school = school;
    }

    public Student(long id, String name, int age, int grade, String major, String school) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.grade = grade;
        this.major = major;
        this.school = school;
    }

    
}
Student

相关文章:

  • 2022-12-23
  • 2019-09-03
  • 2021-10-14
  • 2022-02-05
  • 2021-04-06
  • 2022-12-23
  • 2021-12-02
  • 2021-07-11
猜你喜欢
  • 2022-12-23
  • 2021-07-02
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案