重寫 FastJson 屬性過濾器

          Posted on 2013-09-16 22:36 H2O 閱讀(2854) 評(píng)論(0)  編輯  收藏 所屬分類: java

          Fastjson介紹

          簡(jiǎn)介

          Fastjson是一個(gè)Java語言編寫的高性能功能完善的JSON庫。由阿里巴巴

          高性能

          fastjson采用獨(dú)創(chuàng)的算法,將parse的速度提升到極致,超過所有json庫,包括曾經(jīng)號(hào)稱最快的jackson。并且還超越了google的二進(jìn)制協(xié)議protocol buf。

          支持標(biāo)準(zhǔn)
          • Fastjson完全支持http://json.org的標(biāo)準(zhǔn),也是官方網(wǎng)站收錄的參考實(shí)現(xiàn)之一。

          功能強(qiáng)大
          • 支持各種JDK類型。包括基本類型、JavaBean、Collection、Map、Enum、泛型等。

          • 支持循環(huán)引用

          無依賴
          • 不需要例外額外的jar,能夠直接跑在JDK上。

          支持范圍廣
          • 支持JDK 5、JDK 6、Android、阿里云手機(jī)等環(huán)境。

          開源
          測(cè)試充分
          • fastjson有超過1500個(gè)testcase,每次構(gòu)建都會(huì)跑一遍,豐富的測(cè)試場(chǎng)景保證了功能穩(wěn)定。

          下載

          http://code.alibabatech.com/mvn/releases/com/alibaba/fastjson/


          詳細(xì):fastjson 項(xiàng)目介紹


          背景:剛接觸這個(gè)開源項(xiàng)目不久。遇到問題也不少。不過通過各方詢問、及源碼探究開源得到解決。最近使用FastJson結(jié)合hibernate做項(xiàng)目,發(fā)現(xiàn)關(guān)于對(duì)象的級(jí)聯(lián)屬性的過濾上用的不是很順。當(dāng)然簡(jiǎn)單的屬性過濾 @溫少 已經(jīng)提供了 SimplePropertyPreFilter 使用,使用方法有詳細(xì)說明的。這里我針對(duì)級(jí)聯(lián)屬性的過濾對(duì)該類做了補(bǔ)充。(當(dāng)然你也可以使用注解實(shí)現(xiàn))

          ok、上代碼:


          package com.example.util.fastjson;
             
          import java.util.Date;
          import java.util.HashMap;
          import java.util.Map;
             
          import com.alibaba.fastjson.JSON;
          import com.alibaba.fastjson.serializer.JSONSerializer;
          import com.alibaba.fastjson.serializer.PropertyPreFilter;
          import com.alibaba.fastjson.serializer.SerializerFeature;
          import com.suncompass.example.auth.entity.AuthEmployee;
          import com.suncompass.example.auth.entity.AuthMenu;
          import com.suncompass.framework.base.entity.BaseEntity;
             
          /**
           * 
          @author :晨風(fēng)²º¹³ <br>
           * @Comment : fastjson 針對(duì)類型的屬性選擇過濾器(可以跨層級(jí)) <br>
           
          */
          public class ComplexPropertyPreFilter implements PropertyPreFilter {
                 
              
          private Map<Class<?>, String[]> includes = new HashMap<>();
              
          private Map<Class<?>, String[]> excludes = new HashMap<>();
                 
              
          static {
                  JSON.DEFAULT_GENERATE_FEATURE 
          |= SerializerFeature.DisableCircularReferenceDetect.getMask();
              }
                 
              
          public ComplexPropertyPreFilter() {
                     
              }
                 
              
          public ComplexPropertyPreFilter(Map<Class<?>, String[]> includes) {
                  
          super();
                  
          this.includes = includes;
              }
                 
              
          public boolean apply(JSONSerializer serializer, Object source, String name) {
                     
                  
          //對(duì)象為空。直接放行
                  if (source == null) {
                      
          return true;
                  }
                     
                  
          // 獲取當(dāng)前需要序列化的對(duì)象的類對(duì)象
                  Class<?> clazz = source.getClass();
                     
                  
          // 無需序列的對(duì)象、尋找需要過濾的對(duì)象,可以提高查找層級(jí)
                  
          // 找到不需要的序列化的類型
                  for (Map.Entry<Class<?>, String[]> item : this.excludes.entrySet()) {
                      
          // isAssignableFrom(),用來判斷類型間是否有繼承關(guān)系
                      if (item.getKey().isAssignableFrom(clazz)) {
                          String[] strs 
          = item.getValue();
                             
                          
          // 該類型下 此 name 值無需序列化
                          if (isHave(strs, name)) {
                              
          return false;
                          }
                      }
                  }
                     
                  
          // 需要序列的對(duì)象集合為空 表示 全部需要序列化
                  if (this.includes.isEmpty()) {
                      
          return true;
                  }
                     
                  
          // 需要序列的對(duì)象
                  
          // 找到不需要的序列化的類型
                  for (Map.Entry<Class<?>, String[]> item : this.includes.entrySet()) {
                      
          // isAssignableFrom(),用來判斷類型間是否有繼承關(guān)系
                      if (item.getKey().isAssignableFrom(clazz)) {
                          String[] strs 
          = item.getValue();
                          
          // 該類型下 此 name 值無需序列化
                          if (isHave(strs, name)) {
                              
          return true;
                          }
                      }
                  }
                     
                  
          return false;
              }
                 
              
          /*
               * 此方法有兩個(gè)參數(shù),第一個(gè)是要查找的字符串?dāng)?shù)組,第二個(gè)是要查找的字符或字符串
               
          */
              
          public static boolean isHave(String[] strs, String s) {
                     
                  
          for (int i = 0; i < strs.length; i++) {
                      
          // 循環(huán)查找字符串?dāng)?shù)組中的每個(gè)字符串中是否包含所有查找的內(nèi)容
                      if (strs[i].equals(s)) {
                          
          // 查找到了就返回真,不在繼續(xù)查詢
                          return true;
                      }
                  }
                     
                  
          // 沒找到返回false
                  return false;
              }
                 
              
          public Map<Class<?>, String[]> getIncludes() {
                  
          return includes;
              }
                 
              
          public void setIncludes(Map<Class<?>, String[]> includes) {
                  
          this.includes = includes;
              }
                 
              
          public Map<Class<?>, String[]> getExcludes() {
                  
          return excludes;
              }
                 
              
          public void setExcludes(Map<Class<?>, String[]> excludes) {
                  
          this.excludes = excludes;
              }
                 
              
          public static void main(String[] args) {
                  
          // use instanceOf,用來判斷對(duì)象是否是類的實(shí)例
                  
          // use isAssignableFrom(),用來判斷類型間是否有繼承關(guān)系
                  
          // use isInstance(),用來判斷對(duì)象是否是類的實(shí)例
                     
                  Class
          <?> intClass = Integer.class;
                     
                  
          // Create various objects.
                  String str = "Hello";
                  Date date 
          = new Date();
                  Integer i 
          = new Integer(10);
                     
                  
          // Is str an instance of class Integer?
                  boolean check1 = intClass.isInstance(str);
                  System.out.println(
          "str is an Integer? " + check1);
                     
                  
          // Is date an instance of class Integer?
                  boolean check2 = intClass.isInstance(date);
                  System.out.println(
          "date is an Integer? " + check2);
                     
                  
          // Is i an instance of class Integer?
                  boolean check3 = intClass.isInstance(i);
                  System.out.println(
          "i is an Integer? " + check3);
                     
                  System.out.println(BaseEntity.
          class.isInstance(new AuthEmployee()));
                  System.out.println(AuthEmployee.
          class.isInstance(new AuthMenu()));
                     
                  System.out.println(BaseEntity.
          class.isAssignableFrom(AuthEmployee.class));
              }
          }
          測(cè)試代碼:
          package com.example.auth.test.fastjson;
             
          import java.util.ArrayList;
          import java.util.HashMap;
          import java.util.List;
             
          import com.alibaba.fastjson.JSON;
          import com.example.util.fastjson.ComplexPropertyPreFilter;
             
          public class A {
                 
              
          private Integer aid;
                 
              
          private B b;
                 
              
          private List<C> c = new ArrayList<>();
                 
              
          public A() {
                  
          super();
              }
                 
              
          public static void main(String[] args) {
                  A a 
          = new A();
                  a.setAid(
          1);
                     
                  B b 
          = new B();
                  b.setBid(
          2);
                     
                  a.setB(b);
                  b.setA(a);
                     
                  C c 
          = new C();
                  c.setId(
          3);
                     
                  a.getC().add(c);
                  b.getC().add(c);
                  c.setA(a);
                  c.setB(b);
                     
                  ComplexPropertyPreFilter filter 
          = new ComplexPropertyPreFilter();
                     
                  filter.setExcludes(
          new HashMap<Class<?>, String[]>() {
                         
                      
          private static final long serialVersionUID = -8411128674046835592L;
                         
                      {
                          put(A.
          classnew String[] { "aid" });
                          put(B.
          classnew String[] { "bid""a" });
                          put(C.
          classnew String[] { "a""b" });
                      }
                  });
                         
                  System.out.println(JSON.toJSONString(a, filter));
                     
              }
                 
              
          public Integer getAid() {
                  
          return aid;
              }
                 
              
          public void setAid(Integer aid) {
                  
          this.aid = aid;
              }  
          public B getB() {
                  
          return b;
              }
                 
              
          public void setB(B b) {
                  
          this.b = b;
              }
                 
              
          public List<C> getC() {
                  
          return c;
              }
                 
              
          public void setC(List<C> c) {
                  
          this.c = c;
              }
                 
          }
          package com.example.auth.test.fastjson;
             
          import java.util.ArrayList;
          import java.util.List;
             
          public class B {
                 
              
          private Integer bid;
                 
              
          private A a;
                 
              
          private List<C> c = new ArrayList<>();
                 
              
          public B() {
                  
          super();
              }
                 
              
          public Integer getBid() {
                  
          return bid;
              }
                 
              
          public void setBid(Integer bid) {
                  
          this.bid = bid;
              }
                 
              
          public A getA() {
                  
          return a;
              }
                 
              
          public void setA(A a) {
                  
          this.a = a;
              }
                 
              
          public List<C> getC() {
                  
          return c;
              }
                 
              
          public void setC(List<C> c) {
                  
          this.c = c;
              }
                 
          }
          package com.example.auth.test.fastjson;
             
          public class C {
                 
              
          private Integer id;
                 
              
          private A a;
                 
              
          private B b;
                 
              
          public C() {
                  
          super();
              }
                 
              
          public A getA() {
                  
          return a;
              }
                 
              
          public void setA(A a) {
                  
          this.a = a;
              }
                 
              
          public B getB() {
                  
          return b;
              }
                 
              
          public void setB(B b) {
                  
          this.b = b;
              }
                 
              
          public Integer getId() {
                  
          return id;
              }
                 
              
          public void setId(Integer id) {
                  
          this.id = id;
              }
                 
          }
          ok,代碼已貼好,測(cè)試方法在A類。
          From :
          http://aijava.duapp.com/archives/override-fastjson-propertyprefilter.html

          posts - 0, comments - 21, trackbacks - 0, articles - 101

          Copyright © H2O

          主站蜘蛛池模板: 永新县| 鄂伦春自治旗| 赣州市| 舒兰市| 策勒县| 蒙阴县| 邢台县| 浮梁县| 封开县| 富蕴县| 松原市| 南汇区| 莲花县| 大英县| 西畴县| 岑溪市| 定南县| 铁岭市| 教育| 屏东县| 华宁县| 福鼎市| 化德县| 花莲县| 临颍县| 昌平区| 灵川县| 育儿| 邵阳市| 伊宁市| 乐安县| 宜宾县| 和平区| 巴彦县| 梧州市| 涪陵区| 牟定县| 台江县| 泽库县| 岚皋县| 合阳县|