fastjson的bean屬性過濾器前端
有的時候,咱們在接口開發時,一個完整的bean會包含不少屬性,可是前端接口只須要其中的某幾個屬性時,應該在對json的返回要進行精簡。下面直接看代碼web
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
也許json屬性的輸出序列不是你想要的[默認屬性以字典序列排序],大部分時候序列並非很重要,重要的是數據。this