springboot~alibaba.fastjson2序列化时过滤字段

发布时间 2023-08-10 16:44:43作者: 张占岭

当我们使用阿里的alibaba.fastjson2进行json序列化时,你可以通过方法参数PropertyFilter来实现对字段的获取,将需要序列化的字段写到PropertyFilter对象里,当然也可以将不进行序列化的写到这里,进行逻辑非操作即可

实体

class Person {
    private String firstName;
    private String lastName;
    private int age;

    public Person(String firstName, String lastName, int age) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.age = age;
    }

    public String getFirstName() {
        return firstName;
    }

    public String getLastName() {
        return lastName;
    }

过滤掉字段age,可以使用下面的代码

    public static void main(String[] args) {
        Person person = new Person("John", "Doe", 30);
        PropertyFilter filter = (source, name, value) -> {
            // 过滤掉名为"age"的属性
            return !name.equals("age");
        };
        String json = JSON.toJSONString(person, filter);
        System.out.println(json);
    }

alibaba.fastjson要实现,需要自己写filter了

  • 定义filter对象,实现ObjectSerializer 接口
public class ExcludePropertyFilter implements ObjectSerializer {

    private final String[] excludeProperties;

    public ExcludePropertyFilter(String... excludeProperties) {
        this.excludeProperties = excludeProperties;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
        if (object == null) {
            serializer.getWriter().writeNull(SerializerFeature.WriteNullListAsEmpty, SerializerFeature.WriteNullStringAsEmpty);
            return;
        }
        SerializeWriter out = serializer.getWriter();
        out.write('{');
        serializer.incrementIndent();
        boolean skipComma = true; // 标记是否需要跳过逗号
        FieldInfo[] fields = serializer
            .getFieldSerializerMap()
            .get(object.getClass())
            .getFieldInfos();
        for (FieldInfo fieldInfo : fields) {
            String propertyName = fieldInfo.getName();
            boolean exclude = false;
            for (String excludeProperty : excludeProperties) {
                if (propertyName.equals(excludeProperty)) {
                    exclude = true;
                    break;
                }
            }
            if (exclude) {
                continue; // 跳过需要排除的属性
            }
            if (!skipComma) {
                out.write(',');
            } else {
                skipComma = false;
            }
            out.writeFieldName(propertyName);
            try {
                Object propertyValue = fieldInfo.get(object);
                serializer.write(propertyValue);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        serializer.decrementIdent();
        serializer.setContext(object, fieldName, features);
        out.write('}');
    }
}
  • 同时过滤掉age字段
   public static void main(String[] args) {
        Person person = new Person("John", "Doe", 30);
        String[] excludeProperties = {"age"};
        String json = JSON.toJSONString(person, new ExcludePropertyFilter(excludeProperties));
        System.out.println(json); 
    }