標籤:
fastjson的bean屬性過濾器
有的時候,我們在介面開發時,一個完整的bean會包含很多屬性,但是前端介面只需要其中的某幾個屬性時,應該在對json的返回要進行精簡。下面直接看代碼
package com.base.config;import com.alibaba.fastjson.JSONObject;import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;public class Student { private int id; private String name; private String addr; public Student(int id, String name, String addr) { super(); this.id = id; this.name = name; this.addr = addr; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddr() { return addr; } public void setAddr(String addr) { this.addr = addr; } public static void main(String[] args) { Student s = new Student(1, "test", "銀川市"); SimplePropertyPreFilter filter = new SimplePropertyPreFilter(Student.class, "id","name");//只輸出需要的屬性 SimplePropertyPreFilter filter2 = new SimplePropertyPreFilter(Student.class, "id","addr");//只輸出需要的屬性 System.out.println("filter \n"+JSONObject.toJSONString(s,filter)); System.out.println("------------------------------------"); System.out.println("filter2 \n"+JSONObject.toJSONString(s,filter2)); }}
程式運行結果
filter {"id":1,"name":"test"}------------------------------------filter2 {"addr":"銀川市","id":1}
這樣能最大程度簡化我們需要的bean屬性,來減少不必要的資料量,提示響應速度。
也許json屬性的輸出序列不是你想要的[預設屬性以字典序列排序],大部分時候序列並不是很重要,重要的是資料。
fastjson格式化bean的簡易屬性過濾器