jsonConfig详细使用

一,setCycleDetectionStrategy 防止自包含

Java代码
  1. /**
  2. *这里测试如果含有自包含的时候需要CycleDetectionStrategy
  3. */
  4. publicstaticvoidtestCycleObject(){
  5. CycleObjectobject=newCycleObject();
  6. object.setMemberId("yajuntest");
  7. object.setSex("male");
  8. JsonConfigjsonConfig=newJsonConfig();
  9. jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);
  10. JSONObjectjson=JSONObject.fromObject(object,jsonConfig);
  11. System.out.println(json);
  12. }
  13. publicstaticvoidmain(String[]args){
  14. JsonTest.testCycleObject();
  15. }

其中 CycleObject.java是我自己写的一个类:

Java代码
  1. publicclassCycleObject{
  2. privateStringmemberId;
  3. privateStringsex;
  4. privateCycleObjectme=this;
  5. ……//getters&&setters
  6. }

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

 

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

Java代码
  1. publicstaticvoidtestExcludeProperites(){
  2. Stringstr="{'string':'JSON','integer':1,'double':2.0,'boolean':true}";
  3. JsonConfigjsonConfig=newJsonConfig();
  4. jsonConfig.setExcludes(newString[]{"double","boolean"});
  5. JSONObjectjsonObject=(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. publicstaticvoidmain(String[]args){
  12. JsonTest.testExcludeProperites();
  13. }

 

 

三,setIgnoreDefaultExcludes

Java代码
  1. @SuppressWarnings("unchecked")
  2. publicstaticvoidtestMap(){
  3. Mapmap=newHashMap();
  4. map.put("name","json");
  5. map.put("class","ddd");
  6. JsonConfigconfig=newJsonConfig();
  7. config.setIgnoreDefaultExcludes(true);//默认为false,即过滤默认的key
  8. JSONObjectjsonObject=JSONObject.fromObject(map,config);
  9. System.out.println(jsonObject);
  10. }

上面的代码会把name 和 class都输出。

而去掉setIgnoreDefaultExcludes(true)的话,就只会输出name,不会输出class。

Java代码
  1. privatestaticfinalString[]DEFAULT_EXCLUDES=newString[]{"class","declaringClass",
  2. "metaClass"};//默认会过滤的几个key

 

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

Java代码
  1. publicstaticvoidtestMap(){
  2. Mapmap=newHashMap();
  3. map.put("name","json");
  4. map.put("class","ddd");
  5. map.put("date",newDate());
  6. JsonConfigconfig=newJsonConfig();
  7. config.setIgnoreDefaultExcludes(false);
  8. config.registerJsonBeanProcessor(Date.class,
  9. newJsDateJsonBeanProcessor());//当输出时间格式时,采用和JS兼容的格式输出
  10. JSONObjectjsonObject=JSONObject.fromObject(map,config);
  11. System.out.println(jsonObject);
  12. }

注:JsDateJsonBeanProcessor 是json-lib已经提供的类,我们也可以实现自己的JsonBeanProcessor。

五,registerJsonValueProcessor

 

六,registerDefaultValueProcessor

 

为了演示,首先我自己实现了两个Processor

一个针对Integer

Java代码
  1. publicclassMyDefaultIntegerValueProcessorimplementsDefaultValueProcessor{
  2. publicObjectgetDefaultValue(Classtype){
  3. if(type!=null&&Integer.class.isAssignableFrom(type)){
  4. returnInteger.valueOf(9999);
  5. }
  6. returnJSONNull.getInstance();
  7. }
  8. }

 

一个针对PlainObject(我自定义的类)

Java代码
  1. publicclassMyPlainObjectProcessorimplementsDefaultValueProcessor{
  2. publicObjectgetDefaultValue(Classtype){
  3. if(type!=null&&PlainObject.class.isAssignableFrom(type)){
  4. return"美女"+"瑶瑶";
  5. }
  6. returnJSONNull.getInstance();
  7. }
  8. }

 

以上两个类用于处理当value为null的时候该如何输出。

 

还准备了两个普通的自定义bean

PlainObjectHolder:

Java代码
  1. publicclassPlainObjectHolder{
  2. privatePlainObjectobject;//自定义类型
  3. privateIntegera;//JDK自带的类型
  4. publicPlainObjectgetObject(){
  5. returnobject;
  6. }
  7. publicvoidsetObject(PlainObjectobject){
  8. this.object=object;
  9. }
  10. publicIntegergetA(){
  11. returna;
  12. }
  13. publicvoidsetA(Integera){
  14. this.a=a;
  15. }
  16. }

PlainObject也是我自己定义的类

Java代码
  1. publicclassPlainObject{
  2. privateStringmemberId;
  3. privateStringsex;
  4. publicStringgetMemberId(){
  5. returnmemberId;
  6. }
  7. publicvoidsetMemberId(StringmemberId){
  8. this.memberId=memberId;
  9. }
  10. publicStringgetSex(){
  11. returnsex;
  12. }
  13. publicvoidsetSex(Stringsex){
  14. this.sex=sex;
  15. }
  16. }

 

 

A,如果JSONObject.fromObject(null) 这个参数直接传null进去,json-lib会怎么处理:

Java代码
  1. publicstaticJSONObjectfromObject(Objectobject,JsonConfigjsonConfig){
  2. if(object==null||JSONUtils.isNull(object)){
  3. returnnewJSONObject(true);

看代码是直接返回了一个空的JSONObject,没有用到任何默认值输出。

 

B,其次,我们看如果java对象直接是一个JDK中已经有的类(什么指Enum,Annotation,JSONObject,DynaBean,JSONTokener,JSONString,Map,String,Number,Array),但是值为null ,json-lib如何处理

JSONObject.java

Java代码
  1. }elseif(objectinstanceofEnum){
  2. thrownewJSONException("'object'isanEnum.UseJSONArrayinstead");//不支持枚举
  3. }elseif(objectinstanceofAnnotation||(object!=null&&object.getClass()
  4. .isAnnotation())){
  5. thrownewJSONException("'object'isanAnnotation.");//不支持注解
  6. }elseif(objectinstanceofJSONObject){
  7. return_fromJSONObject((JSONObject)object,jsonConfig);
  8. }elseif(objectinstanceofDynaBean){
  9. return_fromDynaBean((DynaBean)object,jsonConfig);
  10. }elseif(objectinstanceofJSONTokener){
  11. return_fromJSONTokener((JSONTokener)object,jsonConfig);
  12. }elseif(objectinstanceofJSONString){
  13. return_fromJSONString((JSONString)object,jsonConfig);
  14. }elseif(objectinstanceofMap){
  15. return_fromMap((Map)object,jsonConfig);
  16. }elseif(objectinstanceofString){
  17. return_fromString((String)object,jsonConfig);
  18. }elseif(JSONUtils.isNumber(object)||JSONUtils.isBoolean(object)
  19. ||JSONUtils.isString(object)){
  20. returnnewJSONObject();//不支持纯数字
  21. }elseif(JSONUtils.isArray(object)){
  22. thrownewJSONException("'object'isanarray.UseJSONArrayinstead");//不支持数组,需要用JSONArray替代
  23. }else{

根据以上代码,主要发现_fromMap是不支持使用DefaultValueProcessor 的。

原因看代码:

JSONObject.java

Java代码
  1. if(value!=null){//大的前提条件,value不为空
  2. JsonValueProcessorjsonValueProcessor=jsonConfig.findJsonValueProcessor(
  3. value.getClass(),key);
  4. if(jsonValueProcessor!=null){
  5. value=jsonValueProcessor.processObjectValue(key,value,jsonConfig);
  6. if(!JsonVerifier.isValidJsonValue(value)){
  7. thrownewJSONException("ValueisnotavalidJSONvalue."+value);
  8. }
  9. }
  10. setValue(jsonObject,key,value,value.getClass(),jsonConfig);

 

Java代码
  1. privatestaticvoidsetValue(JSONObjectjsonObject,Stringkey,Objectvalue,Classtype,
  2. JsonConfigjsonConfig){
  3. booleanaccumulated=false;
  4. if(value==null){//当value为空的时候使用DefaultValueProcessor
  5. value=jsonConfig.findDefaultValueProcessor(type)
  6. .getDefaultValue(type);
  7. if(!JsonVerifier.isValidJsonValue(value)){
  8. thrownewJSONException("ValueisnotavalidJSONvalue."+value);
  9. }
  10. }
  11. ……

根据我的注释,上面的代码显然是存在矛盾。

 

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

 

C,我们看如果 java 对象是自定义类型的,并且里面的属性包含空值(没赋值,默认是null)也就是上面B还没贴出来的最后一个else

Java代码
  1. else{return_fromBean(object,jsonConfig);}

 

我写了个测试类:

Java代码
  1. publicstaticvoidtestDefaultValueProcessor(){
  2. PlainObjectHolderholder=newPlainObjectHolder();
  3. JsonConfigconfig=newJsonConfig();
  4. config.registerDefaultValueProcessor(PlainObject.class,
  5. newMyPlainObjectProcessor());
  6. config.registerDefaultValueProcessor(Integer.class,
  7. newMyDefaultIntegerValueProcessor());
  8. JSONObjectjson=JSONObject.fromObject(holder,config);
  9. System.out.println(json);
  10. }

 

这种情况的输出值是 {"a":9999,"object":"美女瑶瑶"}
即两个Processor都起作用了。

 

 

 

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

一,ignoreDefaultExcludes

Java代码
  1. publicstaticvoidjson2java(){
  2. StringjsonString="{'name':'hello','class':'ddd'}";
  3. JsonConfigconfig=newJsonConfig();
  4. config.setIgnoreDefaultExcludes(true);//与JAVAToJson的时候一样,不设置class属性无法输出
  5. JSONObjectjson=(JSONObject)JSONSerializer.toJSON(jsonString,config);
  6. System.out.println(json);
  7. }

 

 

========================== JSON 输出的安全问题 ===============

我们做程序的时候主要是使用 Java To Json的方式,下面描述的是 安全性问题:

 

Java代码
  1. @SuppressWarnings("unchecked")
  2. publicstaticvoidtestSecurity(){
  3. Mapmap=newHashMap();
  4. map.put("/"}<IMGsrc='x.jpg'onerror=javascript:alert('说了你不要进来')border=0>{","");
  5. JSONObjectjsonObject=JSONObject.fromObject(map);
  6. System.out.println(jsonObject);
  7. }
Java代码
  1. publicstaticvoidmain(String[]args){
  2. JsonTest.testSecurity();
  3. }

输出的内容:

{"/"}<IMG src='x.jpg' onerror=javascript:alert('说了你不要进来') border=0> {":""}

 

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

 

原文地址:http://yjhexy.javaeye.com/blog/681067

你可能感兴趣的:(config)