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

当我们使用阿里的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); 
    }
posted @   张占岭  阅读(975)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示
历史上的今天:
2019-08-10 java基础文章汇总
2019-08-10 JVM垃圾收集策略与算法
2018-08-10 springboot~Profile开发环境与单元测试用不同的数据库
2017-08-10 LindAgile~缓存拦截器支持类的虚方法了
2016-08-10 Lind.DDD.Manage项目核心技术分享
2013-08-10 我心中的核心组件(可插拔的AOP)~第四回 异常拦截器
2012-08-10 第三回 基类中的方法,应该根据实际情况,虚的虚,抽象的抽象!
点击右上角即可分享
微信分享提示