fastJson 序列化忽略指定字段

-- 方式一@JSONField
public class FastJsonTest {
    @Data
    public static class Person {
        private String name;
        @JSONField(serialize = false)
        private Integer age;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("One");
        person.setAge(18);
        System.out.println(JSON.toJSONString(person));
    }
}
-- 方式二 SimplePropertyPreFilter 保留序列化字段

public class FastJsonTest {
    @Data
    public static class Person {
        private String name;
        private Integer age;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("One");
        person.setAge(18);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Person.class, "name");
        System.out.println(JSON.toJSONString(person, filter));
    }
}
-- 方式三,排除字段
public class FastJsonTest {
    @Data
    public static class Person {
        private String name;
        private Integer age;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("One");
        person.setAge(18);
        SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Person.class);
        filter.getExcludes().add("age");
        System.out.println(JSON.toJSONString(person, filter));
    }
}
-- 属性过滤

public class FastJsonTest {
    @Data
    public static class Person {
        private String name;
        private Integer age;
    }

    public static void main(String[] args) {
        Person person = new Person();
        person.setName("One");
        person.setAge(18);
        PropertyFilter profilter = (object, name, value) -> {
            if (name.equals("age")) {
                // false表示字段将被排除在外
                return false;
            }
            return true;
        };
        System.out.println(JSON.toJSONString(person, profilter));
    }
}
经验分享 程序员 微信小程序 职场和发展