FastJson序列化時忽略特定屬性

來源:互聯網
上載者:User

標籤:des   style   blog   http   color   java   os   ar   art   

 

在之前的工作中,一直用jackson來處理json串轉換的問題,有些時候我們經常有忽略某些屬性的情況,個人比較習慣jackson的註解的方式,而且也是比較靈活的,分別提供了@JsonIgnoreProperties,@JsonIgnore等。

而FastJson中,並沒有提供類似的方式,而是提供了各種filter機制來實現的,具體可以參考:https://github.com/alibaba/fastjson/wiki/%E5%AE%9A%E5%88%B6%E5%BA%8F%E5%88%97%E5%8C%96

 

下面是個小例子:

主要是通過FastJson內建的SimplePropertyPreFilter這個類實現,其他我們自己可以實現上面文檔裡面的各種filter介面

Person.java:

 1 /** 2  *  3  */ 4 package json; 5  6 /** 7  * 測試fastjson序列化時忽略制定屬性 8  *  9  * @author bells10  * 11  */12 public class Person {13 14     private int age;15 16     private String name;17 18     private int height;19 20     private int weight;21 22     public Person() {23 24     }25 26     public Person(int age, String name, int height, int weight) {27         this.age = age;28         this.name = name;29         this.height = height;30         this.weight = weight;31     }32 33     public int getAge() {34         return age;35     }36 37     public void setAge(int age) {38         this.age = age;39     }40 41     public String getName() {42         return name;43     }44 45     public void setName(String name) {46         this.name = name;47     }48 49     public int getHeight() {50         return height;51     }52 53     public void setHeight(int height) {54         this.height = height;55     }56 57     public int getWeight() {58         return weight;59     }60 61     public void setWeight(int weight) {62         this.weight = weight;63     }64 65 }
View Code

Main.java:

 1 /** 2  *  3  */ 4 package json; 5  6 import com.alibaba.fastjson.JSON; 7 import com.alibaba.fastjson.serializer.SimplePropertyPreFilter; 8  9 /**10  * 測試fastjson序列化時忽略制定屬性11  * 12  * @author bells13  * 14  */15 public class Main {16 17     /**18      * @param args19      */20     public static void main(String[] args) {21 22         Person person = new Person(26, "bells", 172, 60);23 24         SimplePropertyPreFilter filter = new SimplePropertyPreFilter(); // 構造方法裡,也可以直接傳需要序列化的屬性名稱字25 26         filter.getExcludes().add("age"); // SimplePropertyPreFilter 裡面有兩個Set,分別為27                                             // excludes和includes,這兩個Set的作用非常明顯。28 29         System.out.println(JSON.toJSONString(person, filter));30 31     }32 33 }

 

FastJson序列化時忽略特定屬性

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.