首页 > 其他分享 >springboot~alibaba.fastjson2序列化时过滤字段

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

时间:2023-08-10 16:44:40浏览次数:36  
标签:fastjson2 springboot age out 序列化 excludeProperties public serializer String

当我们使用阿里的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); 
    }

标签:fastjson2,springboot,age,out,序列化,excludeProperties,public,serializer,String
From: https://www.cnblogs.com/lori/p/17620781.html

相关文章

  • 使用 SpringBoot 进行优雅的数据验证
    JSR-303规范在程序进行数据处理之前,对数据进行准确性校验是我们必须要考虑的事情。尽早发现数据错误,不仅可以防止错误向核心业务逻辑蔓延,而且这种错误非常明显,容易发现解决。JSR303规范(BeanValidation规范)为JavaBean验证定义了相应的元数据模型和API。在应用程序中,通过使......
  • 什么是Redis,如何使用Redis,SpringBoot如何集成Redis
    官网链接:Redis首先简单理解一下1、什么是redisredis是一种开源的、内存中数据结构存储,用作数据库、缓存和消息代理。redis数据结构包含五大数据类型:字符串、散列、列表、集合、带范围查询的排序集合以及三大特殊数据类型:位图、超级日志、地理空间索引。redis内置复制、Lua脚本......
  • SpringBoot3文件管理
    目录一、简介二、工程搭建1、工程结构2、依赖管理三、上传下载1、配置管理2、上传下载四、Excel文件1、Excel创建2、Excel读取3、解析监听4、导入导出五、参考源码标签:上传.下载.Excel.导入.导出;一、简介在项目中,文件管理是常见的复杂功能;首先文件的类型比较多样,处理起来比......
  • 解密SpringBoot3.0:构建易维护的JavaWeb应用
    SpringBoot3.0最新深入浅出从入门到项目实战,突出Web应用痛点解决方案SpringBoot已经成为Java开发中最流行的框架之一,它提供了一种快速构建、易于扩展的方式,使开发人员能够更加专注于业务逻辑而不是繁琐的配置。而最新的SpringBoot3.0版本将进一步改善开发体验,并提供更多的解决方......
  • 序列化
    什么是序列化我们把对象(变量)从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。为什么要序列化1.持久保存状态需知一个软件/程序的执行就在处理一系列状态的变化,在编程语言中,'状......
  • delphi 自带的JSON序列化类
    unitUnit1;interfaceusesWinapi.Windows,Winapi.Messages,System.SysUtils,System.Variants,System.Classes,Vcl.Graphics,Vcl.Controls,Vcl.Forms,Vcl.Dialogs,System.JSON.Serializers,Vcl.StdCtrls;typeTForm1=class(TForm)Memo1:TMemo......
  • Weblogic WLS Core Components 反序列化命令执行漏洞(CVE-2018-2628)
    Vulhub-Docker-Composefileforvulnerabilityenvironment1、介绍名称:WeblogicWLSCoreComponents反序列化命令执行漏洞(CVE-2018-2628)编号:CVE-2018-2628原理:应用:Weblogic 版本:Weblogic10.3.6.0,Weblogic12.1.3.0,Weblogic12.2.1.2,Weblogic12.2.1.32、测试2.......
  • SpringBoot启动项目失败但不报错
    新建的SpringBoot项目,点击启动,项目没有启动成功,但是不报错。如下:._________/\\/___'_____(_)______\\\\(()\___|'_|'_||'_\/_`|\\\\\\/___)||_)|||||||(_||))))'|____......
  • SpringBoot源码实用场景:SpringBoot 3.1.0 环境下 PageHelper 1.4.0不生效问题排查
    1、技术栈:JDK17+SpringBoot3.1.0+PageHelper1.4.01<?xmlversion="1.0"encoding="UTF-8"?>2<project...>3<parent>4<groupId>org.springframework.boot</groupId>5<arti......
  • springboot设置log4j2无效
     log4j2需要在资源文件中正确的写法:错误的写法:下面写法会无效的会使用springboot本身的日志 ......