Chinaunix首页 | 论坛 | 博客
  • 博客访问: 949860
  • 博文数量: 168
  • 博客积分: 3853
  • 博客等级: 中校
  • 技术积分: 1854
  • 用 户 组: 普通用户
  • 注册时间: 2008-01-15 23:50
文章分类

全部博文(168)

文章存档

2014年(12)

2013年(46)

2012年(60)

2011年(11)

2010年(1)

2009年(17)

2008年(21)

我的朋友

分类: Java

2013-02-06 16:28:07

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

 

一,setCycleDetectionStrategy 防止自包含

Java代码  收藏代码
  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是我自己写的一个类:

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的属性

Java代码  收藏代码
  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

Java代码  收藏代码
  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。

Java代码  收藏代码
  1. private static final String[] DEFAULT_EXCLUDES = new String[] { "class""declaringClass",  
  2.       "metaClass" }; // 默认会过滤的几个key  

 

四,registerJsonBeanProcessor 当value类型是从java的一个bean转化过来的时候,可以提供自定义处理器

Java代码  收藏代码
  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

Java代码  收藏代码
  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(我自定义的类)

Java代码  收藏代码
  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:

Java代码  收藏代码
  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 也是我自己定义的类

Java代码  收藏代码
  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会怎么处理:

Java代码  收藏代码
  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

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

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 );  

 

Java代码  收藏代码
  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

Java代码  收藏代码
  1. else {return _fromBean( object, jsonConfig );}  

 

 我写了个测试类:

Java代码  收藏代码
  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

Java代码  收藏代码
  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的方式,下面描述的是 安全性问题:

 

Java代码  收藏代码
  1. @SuppressWarnings("unchecked")  
  2.    public static void testSecurity() {  
  3.        Map map = new HashMap();  
  4.        map.put("\"} {""");  
  5.        JSONObject jsonObject = JSONObject.fromObject(map);  
  6.        System.out.println(jsonObject);  
  7.    }  
 
Java代码  收藏代码
  1. public static void main(String[] args) {  
  2.        JsonTest.testSecurity();  
  3.    }  

 输出的内容:

{"\"} {":"" }

 

如果把这段内容直接贴到记事本里面,命名为 testSecu.html ,然后用浏览器打开发现执行了其中的 js脚本。这样就容易产生XSS安全问题。

阅读(2573) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~