在各自岗位上尽职尽责,无需豪言壮语,默默行动会诠释一切。这世界,虽然没有绝对的公平,但是努力就会增加成功和变好的可能性!而这带着未知变量的可能性,就足以让我们普通人拼命去争取了。
欢迎来到~一支会记忆的笔~博客主页

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 的字段。

posted @ 2019-09-18 17:23  一支会记忆的笔  阅读(1730)  评论(0编辑  收藏  举报
返回顶部
【学无止境❤️谦卑而行】