JSON lib 里JsonConfig詳解


一,setCycleDetectionStrategy 防止自包含

  1. /** 
  2.     * 這里測試如果含有自包含的時候需要CycleDetectionStrategy 
  3.     */  
  4.    public static void testCycleObject() {  
  5.        CycleObject object = new CycleObject();  
  6.        object.setMemberId("yajuntest");  
  7.        object.setSex("male");  
  8.        JsonConfig jsonConfig = new JsonConfig();  
  9.        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);  
  10.   
  11.        JSONObject json = JSONObject.fromObject(object, jsonConfig);  
  12.        System.out.println(json);  
  13.    }  
  14.   
  15.    public static void main(String[] args) {  
  16.               JsonTest.testCycleObject();  
  17.    }  

 其中 CycleObject.java是我自己寫的一個類:

  1. public class CycleObject {  
  2.   
  3.     private String      memberId;  
  4.     private String      sex;  
  5.     private CycleObject me = this;  
  6. …… // getters && setters  
  7. }  

 輸出 {"sex":"male","memberId":"yajuntest","me":null}

 

二,setExcludes:排除需要序列化成json的屬性

  1. public static void testExcludeProperites() {  
  2.        String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";  
  3.        JsonConfig jsonConfig = new JsonConfig();  
  4.        jsonConfig.setExcludes(new String[] { "double", "boolean" });  
  5.        JSONObject jsonObject = (JSONObject) JSONSerializer.toJSON(str, jsonConfig);  
  6.        System.out.println(jsonObject.getString("string"));  
  7.        System.out.println(jsonObject.getInt("integer"));  
  8.        System.out.println(jsonObject.has("double"));  
  9.        System.out.println(jsonObject.has("boolean"));  
  10.    }  
  11.   
  12.    public static void main(String[] args) {  
  13.        JsonTest.testExcludeProperites();  
  14.    }  

 

 

三,setIgnoreDefaultExcludes

  1. @SuppressWarnings("unchecked")  
  2.     public static void testMap() {  
  3.         Map map = new HashMap();  
  4.         map.put("name", "json");  
  5.         map.put("class", "ddd");  
  6.         JsonConfig config = new JsonConfig();  
  7.         config.setIgnoreDefaultExcludes(true);  //默認為false,即過濾默認的key  
  8.         JSONObject jsonObject = JSONObject.fromObject(map,config);  
  9.         System.out.println(jsonObject);  
  10.           
  11.     }  

上面的代碼會把name 和 class都輸出。

而去掉setIgnoreDefaultExcludes(true)的話,就只會輸出name,不會輸出class。

  1. private static final String[] DEFAULT_EXCLUDES = new String[] { "class", "declaringClass",  
  2.       "metaClass" }; // 默認會過濾的幾個key  

 

四,registerJsonBeanProcessor 當value類型是從java的一個bean轉化過來的時候,可以提供自定義處理器

  1. public static void testMap() {  
  2.     Map map = new HashMap();  
  3.     map.put("name", "json");  
  4.     map.put("class", "ddd");  
  5.     map.put("date", new Date());  
  6.     JsonConfig config = new JsonConfig();  
  7.     config.setIgnoreDefaultExcludes(false);  
  8.     config.registerJsonBeanProcessor(Date.class,  
  9.             new JsDateJsonBeanProcessor()); // 當輸出時間格式時,采用和JS兼容的格式輸出  
  10.     JSONObject jsonObject = JSONObject.fromObject(map, config);  
  11.     System.out.println(jsonObject);  
  12. }  

 注:JsDateJsonBeanProcessor 是json-lib已經提供的類,我們也可以實現自己的JsonBeanProcessor。

五,registerJsonValueProcessor

 

六,registerDefaultValueProcessor

 

為了演示,首先我自己實現了兩個 Processor

一個針對Integer

  1. public class MyDefaultIntegerValueProcessor implements DefaultValueProcessor {  
  2.   
  3.     public Object getDefaultValue(Class type) {  
  4.         if (type != null && Integer.class.isAssignableFrom(type)) {  
  5.             return Integer.valueOf(9999);  
  6.         }  
  7.         return JSONNull.getInstance();  
  8.     }  
  9.   
  10. }  

 

一個針對PlainObject(我自定義的類)

  1. public class MyPlainObjectProcessor implements DefaultValueProcessor {  
  2.   
  3.     public Object getDefaultValue(Class type) {  
  4.         if (type != null && PlainObject.class.isAssignableFrom(type)) {  
  5.             return "美女" + "瑤瑤";  
  6.         }  
  7.         return JSONNull.getInstance();  
  8.     }  
  9. }  

 

以上兩個類用於處理當value為null的時候該如何輸出。

 

還准備了兩個普通的自定義bean

PlainObjectHolder:

  1. public class PlainObjectHolder {  
  2.   
  3.     private PlainObject object; // 自定義類型  
  4.     private Integer a; // JDK自帶的類型  
  5.   
  6.     public PlainObject getObject() {  
  7.         return object;  
  8.     }  
  9.   
  10.     public void setObject(PlainObject object) {  
  11.         this.object = object;  
  12.     }  
  13.   
  14.     public Integer getA() {  
  15.         return a;  
  16.     }  
  17.   
  18.     public void setA(Integer a) {  
  19.         this.a = a;  
  20.     }  
  21.   
  22. }  

PlainObject 也是我自己定義的類

  1. public class PlainObject {  
  2.   
  3.     private String memberId;  
  4.     private String sex;  
  5.   
  6.     public String getMemberId() {  
  7.         return memberId;  
  8.     }  
  9.   
  10.     public void setMemberId(String memberId) {  
  11.         this.memberId = memberId;  
  12.     }  
  13.   
  14.     public String getSex() {  
  15.         return sex;  
  16.     }  
  17.   
  18.     public void setSex(String sex) {  
  19.         this.sex = sex;  
  20.     }  
  21.   
  22. }  

 

 

A,如果JSONObject.fromObject(null) 這個參數直接傳null進去,json-lib會怎么處理:

  1. public static JSONObject fromObject( Object object, JsonConfig jsonConfig ) {  
  2.      if( object == null || JSONUtils.isNull( object ) ){  
  3.         return new JSONObject( true );  

 看代碼是直接返回了一個空的JSONObject,沒有用到任何默認值輸出。

 

B,其次,我們看如果java對象直接是一個JDK中已經有的類(什么指 Enum,Annotation,JSONObject,DynaBean,JSONTokener,JSONString,Map,String,Number,Array),但是值為null ,json-lib如何處理

 JSONObject.java

  1. }else if( object instanceof Enum ){  
  2.        throw new JSONException( "'object' is an Enum. Use JSONArray instead" ); // 不支持枚舉  
  3.     }else if( object instanceof Annotation || (object != null && object.getClass()  
  4.           .isAnnotation()) ){  
  5.        throw new JSONException( "'object' is an Annotation." ); // 不支持 注解  
  6.     }else if( object instanceof JSONObject ){  
  7.        return _fromJSONObject( (JSONObject) object, jsonConfig );  
  8.     }else if( object instanceof DynaBean ){  
  9.        return _fromDynaBean( (DynaBean) object, jsonConfig );  
  10.     }else if( object instanceof JSONTokener ){  
  11.        return _fromJSONTokener( (JSONTokener) object, jsonConfig );  
  12.     }else if( object instanceof JSONString ){  
  13.        return _fromJSONString( (JSONString) object, jsonConfig );  
  14.     }else if( object instanceof Map ){  
  15.        return _fromMap( (Map) object, jsonConfig );  
  16.     }else if( object instanceof String ){  
  17.        return _fromString( (String) object, jsonConfig );  
  18.     }else if( JSONUtils.isNumber( object ) || JSONUtils.isBoolean( object )  
  19.           || JSONUtils.isString( object ) ){  
  20.        return new JSONObject();  // 不支持純數字  
  21.     }else if( JSONUtils.isArray( object ) ){  
  22.        throw new JSONException( "'object' is an array. Use JSONArray instead" ); //不支持數組,需要用JSONArray替代  
  23.     }else{  

根據以上代碼,主要發現_fromMap是不支持使用DefaultValueProcessor 的。

原因看代碼:

JSONObject.java

  1. if( value != null ){ //大的前提條件,value不為空  
  2.               JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(  
  3.                     value.getClass(), key );  
  4.               if( jsonValueProcessor != null ){  
  5.                  value = jsonValueProcessor.processObjectValue( key, value, jsonConfig );  
  6.                  if( !JsonVerifier.isValidJsonValue( value ) ){  
  7.                     throw new JSONException( "Value is not a valid JSON value. " + value );  
  8.                  }  
  9.               }  
  10.               setValue( jsonObject, key, value, value.getClass(), jsonConfig );  

 

  1.  private static void setValue( JSONObject jsonObject, String key, Object value, Class type,  
  2.          JsonConfig jsonConfig ) {  
  3.       boolean accumulated = false;  
  4.       if( value == null ){ // 當 value為空的時候使用DefaultValueProcessor  
  5.          value = jsonConfig.findDefaultValueProcessor( type )  
  6.                .getDefaultValue( type );  
  7.          if( !JsonVerifier.isValidJsonValue( value ) ){  
  8.             throw new JSONException( "Value is not a valid JSON value. " + value );  
  9.          }  
  10.       }  
  11. ……  

根據我的注釋, 上面的代碼顯然是存在矛盾。

 

_fromDynaBean是支持DefaultValueProcessor的和下面的C是一樣的。

 

C,我們看如果 java 對象是自定義類型的,並且里面的屬性包含空值(沒賦值,默認是null)也就是上面B還沒貼出來的最后一個else

  1. else {return _fromBean( object, jsonConfig );}  

 

 我寫了個測試類:

  1. public static void testDefaultValueProcessor() {  
  2.         PlainObjectHolder holder = new PlainObjectHolder();  
  3.         JsonConfig config = new JsonConfig();  
  4.         config.registerDefaultValueProcessor(PlainObject.class,  
  5.                 new MyPlainObjectProcessor());  
  6.         config.registerDefaultValueProcessor(Integer.class,  
  7.                 new MyDefaultIntegerValueProcessor());  
  8.         JSONObject json = JSONObject.fromObject(holder, config);  
  9.         System.out.println(json);  
  10.     }  

 

這種情況的輸出值是 {"a":9999,"object":"美女瑤瑤"}
即兩個Processor都起作用了。

 

 

 

========================== Json To Java ===============

一,ignoreDefaultExcludes

  1. public static void json2java() {  
  2.         String jsonString = "{'name':'hello','class':'ddd'}";  
  3.         JsonConfig config = new JsonConfig();  
  4.         config.setIgnoreDefaultExcludes(true); // 與JAVA To Json的時候一樣,不設置class屬性無法輸出  
  5.         JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonString,config);  
  6.         System.out.println(json);  
  7.     }  

 

 

========================== JSON 輸出的安全問題 ===============

我們做程序的時候主要是使用 Java To Json的方式,下面描述的是 安全性問題:

 

  1. @SuppressWarnings("unchecked")  
  2.    public static void testSecurity() {  
  3.        Map map = new HashMap();  
  4.        map.put("\"}<IMG src='x.jpg' onerror=javascript:alert('說了你不要進來') border=0> {", "");  
  5.        JSONObject jsonObject = JSONObject.fromObject(map);  
  6.        System.out.println(jsonObject);  
  7.    }  

 

  1. public static void main(String[] args) {  
  2.        JsonTest.testSecurity();  
  3.    }  

 輸出的內容:

{"\"}<IMG src='x.jpg' onerror=javascript:alert('說了你不要進來') border=0> {":"" }

 

如果把這段內容直接貼到記事本里面,命名為 testSecu.html ,然后用瀏覽器打開發現執行了其中的 js腳本。這樣就容易產生XSS安全問題。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM