zoukankan      html  css  js  c++  java
  • FastJson只序列化java对象的部分属性

    实体类

    public class Student {
      
      private int id;
      private String name;
      private int age;
    
      //get set方法略
    }
    如下方法:
    Student student = new Student(0, "Aaron", 24);
    System.out.println(JSON.toJSONString(student,true));
    输出为:
    {
    "age":24,
    "id":0,
    "name":"Aaron"
    }

    如果我们想要将实体类中的某个字段或某几个不进行解析呢?那么我们可以使用transient 关键字,来标记它为不需要的,在fastjson中还提供了一种便捷的方法来自定义我们需要序列化的字段,

    SimplePropertyPreFilter filter = new SimplePropertyPreFilter(实体类.class, "字段1","字段2"); //字段为我们需要序列化的字段,如果实体类中没有改字段则不解析放弃该字段而不会报错。
    SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Student.class, "id","age");
    String jsonStu =JSON.toJSONString(students,filter);

    这样就只会序列化 id和age 的字段。

  • 相关阅读:
    CTSC2018滚粗记
    HNOI2018游记
    NOIWC 2018游记
    PKUWC2018滚粗记
    HNOI2017 游记
    NOIP2017题解
    [HNOI2017]抛硬币
    [HNOI2017]大佬
    NOIP难题汇总
    [NOI2013]树的计数
  • 原文地址:https://www.cnblogs.com/JonaLin/p/11543858.html
Copyright © 2011-2022 走看看