jsonConfig详细使用
一,setCycleDetectionStrategy 防止自包含
Java代码- /***这里测试如果含有自包含的时候需要CycleDetectionStrategy*/publicstaticvoidtestCycleObject(){CycleObjectobject=newCycleObject();object.setMemberId("yajuntest");object.setSex("male");JsonConfigjsonConfig=newJsonConfig();jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);JSONObjectjson=JSONObject.fromObject(object,jsonConfig);System.out.println(json);}publicstaticvoidmain(String[]args){JsonTest.testCycleObject();}
其中 CycleObject.java是我自己写的一个类:
Java代码- publicclassCycleObject{privateStringmemberId;privateStringsex;privateCycleObjectme=this;……//getters&&setters}
输出 {"sex":"male","memberId":"yajuntest","me":null}
?
二,setExcludes:排除需要序列化成json的属性
Java代码- publicstaticvoidtestExcludeProperites(){Stringstr="{'string':'JSON','integer':1,'double':2.0,'boolean':true}";JsonConfigjsonConfig=newJsonConfig();jsonConfig.setExcludes(newString[]{"double","boolean"});JSONObjectjsonObject=(JSONObject)JSONSerializer.toJSON(str,jsonConfig);System.out.println(jsonObject.getString("string"));System.out.println(jsonObject.getInt("integer"));System.out.println(jsonObject.has("double"));System.out.println(jsonObject.has("boolean"));}publicstaticvoidmain(String[]args){JsonTest.testExcludeProperites();}
?
?
三,setIgnoreDefaultExcludes
Java代码- @SuppressWarnings("unchecked")publicstaticvoidtestMap(){Mapmap=newHashMap();map.put("name","json");map.put("class","ddd");JsonConfigconfig=newJsonConfig();config.setIgnoreDefaultExcludes(true);//默认为false,即过滤默认的keyJSONObjectjsonObject=JSONObject.fromObject(map,config);System.out.println(jsonObject);}
上面的代码会把name 和 class都输出。
而去掉setIgnoreDefaultExcludes(true)的话,就只会输出name,不会输出class。
Java代码- privatestaticfinalString[]DEFAULT_EXCLUDES=newString[]{"class","declaringClass","metaClass"};//默认会过滤的几个key
?
四,registerJsonBeanProcessor 当value类型是从java的一个bean转化过来的时候,可以提供自定义处理器
Java代码- publicstaticvoidtestMap(){Mapmap=newHashMap();map.put("name","json");map.put("class","ddd");map.put("date",newDate());JsonConfigconfig=newJsonConfig();config.setIgnoreDefaultExcludes(false);config.registerJsonBeanProcessor(Date.class,newJsDateJsonBeanProcessor());//当输出时间格式时,采用和JS兼容的格式输出JSONObjectjsonObject=JSONObject.fromObject(map,config);System.out.println(jsonObject);}
注:JsDateJsonBeanProcessor 是json-lib已经提供的类,我们也可以实现自己的JsonBeanProcessor。
五,registerJsonValueProcessor
?
六,registerDefaultValueProcessor
?
为了演示,首先我自己实现了两个Processor
一个针对Integer
Java代码- publicclassMyDefaultIntegerValueProcessorimplementsDefaultValueProcessor{publicObjectgetDefaultValue(Classtype){if(type!=null&&Integer.class.isAssignableFrom(type)){returnInteger.valueOf(9999);}returnJSONNull.getInstance();}}
?
一个针对PlainObject(我自定义的类)
Java代码- publicclassMyPlainObjectProcessorimplementsDefaultValueProcessor{publicObjectgetDefaultValue(Classtype){if(type!=null&&PlainObject.class.isAssignableFrom(type)){return"美女"+"瑶瑶";}returnJSONNull.getInstance();}}
?
以上两个类用于处理当value为null的时候该如何输出。
?
还准备了两个普通的自定义bean
PlainObjectHolder:
Java代码- publicclassPlainObjectHolder{privatePlainObjectobject;//自定义类型privateIntegera;//JDK自带的类型publicPlainObjectgetObject(){returnobject;}publicvoidsetObject(PlainObjectobject){this.object=object;}publicIntegergetA(){returna;}publicvoidsetA(Integera){this.a=a;}}
PlainObject也是我自己定义的类
Java代码- publicclassPlainObject{privateStringmemberId;privateStringsex;publicStringgetMemberId(){returnmemberId;}publicvoidsetMemberId(StringmemberId){this.memberId=memberId;}publicStringgetSex(){returnsex;}publicvoidsetSex(Stringsex){this.sex=sex;}}
?
?
A,如果JSONObject.fromObject(null) 这个参数直接传null进去,json-lib会怎么处理:
Java代码- publicstaticJSONObjectfromObject(Objectobject,JsonConfigjsonConfig){if(object==null||JSONUtils.isNull(object)){returnnewJSONObject(true);
看代码是直接返回了一个空的JSONObject,没有用到任何默认值输出。
?
B,其次,我们看如果java对象直接是一个JDK中已经有的类(什么指Enum,Annotation,JSONObject,DynaBean,JSONTokener,JSONString,Map,String,Number,Array),但是值为null ,json-lib如何处理
JSONObject.java
Java代码- }elseif(objectinstanceofEnum){thrownewJSONException("'object'isanEnum.UseJSONArrayinstead");//不支持枚举}elseif(objectinstanceofAnnotation||(object!=null&&object.getClass().isAnnotation())){thrownewJSONException("'object'isanAnnotation.");//不支持注解}elseif(objectinstanceofJSONObject){return_fromJSONObject((JSONObject)object,jsonConfig);}elseif(objectinstanceofDynaBean){return_fromDynaBean((DynaBean)object,jsonConfig);}elseif(objectinstanceofJSONTokener){return_fromJSONTokener((JSONTokener)object,jsonConfig);}elseif(objectinstanceofJSONString){return_fromJSONString((JSONString)object,jsonConfig);}elseif(objectinstanceofMap){return_fromMap((Map)object,jsonConfig);}elseif(objectinstanceofString){return_fromString((String)object,jsonConfig);}elseif(JSONUtils.isNumber(object)||JSONUtils.isBoolean(object)||JSONUtils.isString(object)){returnnewJSONObject();//不支持纯数字}elseif(JSONUtils.isArray(object)){thrownewJSONException("'object'isanarray.UseJSONArrayinstead");//不支持数组,需要用JSONArray替代}else{
根据以上代码,主要发现_fromMap是不支持使用DefaultValueProcessor 的。
原因看代码:
JSONObject.java
Java代码- if(value!=null){//大的前提条件,value不为空JsonValueProcessorjsonValueProcessor=jsonConfig.findJsonValueProcessor(value.getClass(),key);if(jsonValueProcessor!=null){value=jsonValueProcessor.processObjectValue(key,value,jsonConfig);if(!JsonVerifier.isValidJsonValue(value)){thrownewJSONException("ValueisnotavalidJSONvalue."+value);}}setValue(jsonObject,key,value,value.getClass(),jsonConfig);
?
Java代码- privatestaticvoidsetValue(JSONObjectjsonObject,Stringkey,Objectvalue,Classtype,JsonConfigjsonConfig){booleanaccumulated=false;if(value==null){//当value为空的时候使用DefaultValueProcessorvalue=jsonConfig.findDefaultValueProcessor(type).getDefaultValue(type);if(!JsonVerifier.isValidJsonValue(value)){thrownewJSONException("ValueisnotavalidJSONvalue."+value);}}……
根据我的注释,上面的代码显然是存在矛盾。
?
_fromDynaBean是支持DefaultValueProcessor的和下面的C是一样的。
?
C,我们看如果 java 对象是自定义类型的,并且里面的属性包含空值(没赋值,默认是null)也就是上面B还没贴出来的最后一个else
Java代码- else{return_fromBean(object,jsonConfig);}
?
我写了个测试类:
Java代码- publicstaticvoidtestDefaultValueProcessor(){PlainObjectHolderholder=newPlainObjectHolder();JsonConfigconfig=newJsonConfig();config.registerDefaultValueProcessor(PlainObject.class,newMyPlainObjectProcessor());config.registerDefaultValueProcessor(Integer.class,newMyDefaultIntegerValueProcessor());JSONObjectjson=JSONObject.fromObject(holder,config);System.out.println(json);}
?
这种情况的输出值是 {"a":9999,"object":"美女瑶瑶"}
即两个Processor都起作用了。
?
?
?
========================== Json To Java ===============
一,ignoreDefaultExcludes
Java代码- publicstaticvoidjson2java(){StringjsonString="{'name':'hello','class':'ddd'}";JsonConfigconfig=newJsonConfig();config.setIgnoreDefaultExcludes(true);//与JAVAToJson的时候一样,不设置class属性无法输出JSONObjectjson=(JSONObject)JSONSerializer.toJSON(jsonString,config);System.out.println(json);}
?
?
========================== JSON 输出的安全问题 ===============
我们做程序的时候主要是使用 Java To Json的方式,下面描述的是 安全性问题:
?
Java代码- @SuppressWarnings("unchecked")publicstaticvoidtestSecurity(){Mapmap=newHashMap();map.put("/"}<IMGsrc='x.jpg'onerror=javascript:alert('说了你不要进来')border=0>{","");JSONObjectjsonObject=JSONObject.fromObject(map);System.out.println(jsonObject);}
- publicstaticvoidmain(String[]args){JsonTest.testSecurity();}
输出的内容:
{"/"}<IMG src='x.jpg' onerror=javascript:alert('说了你不要进来') border=0> {":""}?
如果把这段内容直接贴到记事本里面,命名为 testSecu.html ,然后用浏览器打开发现执行了其中的 js脚本。这样就容易产生XSS安全问题。
?
原文地址:http://yjhexy.javaeye.com/blog/681067