fastjson格式化bean的簡易屬性過濾器

來源:互聯網
上載者:User

標籤:

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的簡易屬性過濾器

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.