`
yjhexy
  • 浏览: 327014 次
  • 性别: Icon_minigender_1
  • 来自: 火星
社区版块
存档分类
最新评论

json-lib 之jsonConfig详细使用

阅读更多

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

 

一,setCycleDetectionStrategy 防止自包含

 /**
     * 这里测试如果含有自包含的时候需要CycleDetectionStrategy
     */
    public static void testCycleObject() {
        CycleObject object = new CycleObject();
        object.setMemberId("yajuntest");
        object.setSex("male");
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);

        JSONObject json = JSONObject.fromObject(object, jsonConfig);
        System.out.println(json);
    }

    public static void main(String[] args) {
               JsonTest.testCycleObject();
    }

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

public class CycleObject {

    private String      memberId;
    private String      sex;
    private CycleObject me = this;
…… // getters && setters
}

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

 

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

 public static void testExcludeProperites() {
        String str = "{'string':'JSON', 'integer': 1, 'double': 2.0, 'boolean': true}";
        JsonConfig jsonConfig = new JsonConfig();
        jsonConfig.setExcludes(new String[] { "double", "boolean" });
        JSONObject jsonObject = (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"));
    }

    public static void main(String[] args) {
        JsonTest.testExcludeProperites();
    }

 

 

三,setIgnoreDefaultExcludes

@SuppressWarnings("unchecked")
	public static void testMap() {
		Map map = new HashMap();
		map.put("name", "json");
		map.put("class", "ddd");
		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(true);  //默认为false,即过滤默认的key
		JSONObject jsonObject = JSONObject.fromObject(map,config);
		System.out.println(jsonObject);
		
	}

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

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

   private static final String[] DEFAULT_EXCLUDES = new String[] { "class", "declaringClass",
         "metaClass" }; // 默认会过滤的几个key

 

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

	public static void testMap() {
		Map map = new HashMap();
		map.put("name", "json");
		map.put("class", "ddd");
		map.put("date", new Date());
		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(false);
		config.registerJsonBeanProcessor(Date.class,
				new JsDateJsonBeanProcessor()); // 当输出时间格式时,采用和JS兼容的格式输出
		JSONObject jsonObject = JSONObject.fromObject(map, config);
		System.out.println(jsonObject);
	}

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

五,registerJsonValueProcessor

 

六,registerDefaultValueProcessor

 

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

一个针对Integer

public class MyDefaultIntegerValueProcessor implements DefaultValueProcessor {

	public Object getDefaultValue(Class type) {
		if (type != null && Integer.class.isAssignableFrom(type)) {
			return Integer.valueOf(9999);
		}
		return JSONNull.getInstance();
	}

}

 

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

public class MyPlainObjectProcessor implements DefaultValueProcessor {

	public Object getDefaultValue(Class type) {
		if (type != null && PlainObject.class.isAssignableFrom(type)) {
			return "美女" + "瑶瑶";
		}
		return JSONNull.getInstance();
	}
}

 

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

 

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

PlainObjectHolder:

public class PlainObjectHolder {

	private PlainObject object; // 自定义类型
	private Integer a; // JDK自带的类型

	public PlainObject getObject() {
		return object;
	}

	public void setObject(PlainObject object) {
		this.object = object;
	}

	public Integer getA() {
		return a;
	}

	public void setA(Integer a) {
		this.a = a;
	}

}

PlainObject 也是我自己定义的类

public class PlainObject {

    private String memberId;
    private String sex;

    public String getMemberId() {
        return memberId;
    }

    public void setMemberId(String memberId) {
        this.memberId = memberId;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

}

 

 

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

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

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

 

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

 JSONObject.java

  }else if( object instanceof Enum ){
         throw new JSONException( "'object' is an Enum. Use JSONArray instead" ); // 不支持枚举
      }else if( object instanceof Annotation || (object != null && object.getClass()
            .isAnnotation()) ){
         throw new JSONException( "'object' is an Annotation." ); // 不支持 注解
      }else if( object instanceof JSONObject ){
         return _fromJSONObject( (JSONObject) object, jsonConfig );
      }else if( object instanceof DynaBean ){
         return _fromDynaBean( (DynaBean) object, jsonConfig );
      }else if( object instanceof JSONTokener ){
         return _fromJSONTokener( (JSONTokener) object, jsonConfig );
      }else if( object instanceof JSONString ){
         return _fromJSONString( (JSONString) object, jsonConfig );
      }else if( object instanceof Map ){
         return _fromMap( (Map) object, jsonConfig );
      }else if( object instanceof String ){
         return _fromString( (String) object, jsonConfig );
      }else if( JSONUtils.isNumber( object ) || JSONUtils.isBoolean( object )
            || JSONUtils.isString( object ) ){
         return new JSONObject();  // 不支持纯数字
      }else if( JSONUtils.isArray( object ) ){
         throw new JSONException( "'object' is an array. Use JSONArray instead" ); //不支持数组,需要用JSONArray替代
      }else{

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

原因看代码:

JSONObject.java

 if( value != null ){ //大的前提条件,value不为空
               JsonValueProcessor jsonValueProcessor = jsonConfig.findJsonValueProcessor(
                     value.getClass(), key );
               if( jsonValueProcessor != null ){
                  value = jsonValueProcessor.processObjectValue( key, value, jsonConfig );
                  if( !JsonVerifier.isValidJsonValue( value ) ){
                     throw new JSONException( "Value is not a valid JSON value. " + value );
                  }
               }
               setValue( jsonObject, key, value, value.getClass(), jsonConfig );

 

 private static void setValue( JSONObject jsonObject, String key, Object value, Class type,
         JsonConfig jsonConfig ) {
      boolean accumulated = false;
      if( value == null ){ // 当 value为空的时候使用DefaultValueProcessor
         value = jsonConfig.findDefaultValueProcessor( type )
               .getDefaultValue( type );
         if( !JsonVerifier.isValidJsonValue( value ) ){
            throw new JSONException( "Value is not a valid JSON value. " + value );
         }
      }
……

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

 

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

 

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

else {return _fromBean( object, jsonConfig );}

 

 我写了个测试类:

public static void testDefaultValueProcessor() {
		PlainObjectHolder holder = new PlainObjectHolder();
		JsonConfig config = new JsonConfig();
		config.registerDefaultValueProcessor(PlainObject.class,
				new MyPlainObjectProcessor());
		config.registerDefaultValueProcessor(Integer.class,
				new MyDefaultIntegerValueProcessor());
		JSONObject json = JSONObject.fromObject(holder, config);
		System.out.println(json);
	}

 

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

 

 

 

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

一,ignoreDefaultExcludes

public static void json2java() {
		String jsonString = "{'name':'hello','class':'ddd'}";
		JsonConfig config = new JsonConfig();
		config.setIgnoreDefaultExcludes(true); // 与JAVA To Json的时候一样,不设置class属性无法输出
		JSONObject json = (JSONObject) JSONSerializer.toJSON(jsonString,config);
		System.out.println(json);
	}

 

 

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

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

 

 @SuppressWarnings("unchecked")
    public static void testSecurity() {
        Map map = new HashMap();
        map.put("\"}<IMG src='x.jpg' onerror=javascript:alert('说了你不要进来') border=0> {", "");
        JSONObject jsonObject = JSONObject.fromObject(map);
        System.out.println(jsonObject);
    }
 
 public static void main(String[] args) {
        JsonTest.testSecurity();
    }

 输出的内容:

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

 

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

 

分享到:
评论
1 楼 leiyunshi2008163.co 2011-02-11  
这篇文章很有深度,研究json-lib代码提供了帮助。

相关推荐

    改良版的json-lib2.4

    大家都知道jsonlib2.4之后有了属性过滤的功能,就是当把一个bean转成json的时候能指定哪些属性输出哪些不输出,不过代码很难看,如下 JsonConfig config = new JsonConfig(); config.setJsonPropertyFilter(new ...

    json-lib-2.1 2.2 2.3 2.4-jdk15

    JSONArray.fromObject(map)报错:Could not initialize class net.sf.json.JsonConfig。ireport 需要高于2.1版本的包。于是就找了这些包。最后2.2.2适合

    json-lib出现There is a cycle in the hierarchy解决办法

    设置JSON-LIB让其过滤掉引起循环的字段。 Java代码 代码如下: JsonConfig config = new JsonConfig(); config.setIgnoreDefaultExcludes(false); config.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT)...

    swift-JSONConfig-一个Swift3JSON配置读取库

    JSON Config - 一个Swift 3 JSON配置读取库。读取JSON文件从服务器端配置

    springboot-json-config

    springboot-json-configconfig.json mysql Redis动态配置 不通过spring默认配置,并使用通用mapper(tk.mapper)

    ezmorph.jar v1.0.6免费版.zip

    ezmorph.jar包是在使用json时候将会用到jar包,缺少这个包可能导致Could not initialize class net.sf.json.JsonConfig,给大家提供ezmorph-1.0.6.jar,有需要的赶快下载吧! ezmorph.jar基本简介 EZMorph是一个...

    JsonConfig:使用JSON和C#4.0动态功能的简单配置库

    JsonConfig自述文件关于JsonConfig是一个易于使用的配置库,它允许C#/。NET应用程序使用基于JSON的配置文件,而不必使用繁琐的web.config / application.config xml文件。 它基于JsonFX和C#4.0动态功能。 允许将...

    JSON net.sf.json jar包

    JSON net.sf.json 依赖的jar包 亲测可用 一次导入所有jar包

    java解析json

    json-lib-2.4-jdk15 demo: package com; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import ...

    java jsonto对象互转

    JSONArray jsonArray = JSONArray.fromObject(jsonString, jsonConfig); JSONObject jsonObject; Object pojoValue; List&lt;T&gt; list = new ArrayList(); for (int i = 0; i (); i++) { jsonObject = jsonArray....

    JsonConfig:基于json的配置框架

    配置文件JsonConfig 是一个简单的配置框架,基于 json 和 .NET Framework 4.0+ 中可用的动态类型入门在您的项目中,添加对 JsonConfig.dll 的引用使用 json 格式的配置将名为“app.json.config”的文件添加到您的...

    net.sf.json依赖包

    在用到net.sf.json的时候有时候会因为缺少依赖库而报错,此时可以试试这个包

    json所用到的jar包

    json开发所需要的jar包,fastjson-1.2.2.jar,fastjson-1.2.2-sources.jar,json.jar。不用到处找了

    java后端返回json给前端

    java后端返回json给前端,包含对象JsonObject,JsonConfig,JsonArray.

    ezmorph-1.0.6.jar

    使用json时候将会用到的一个jar包,发现这个包在网上提供的比较少.缺少这个包可能导致Could not initialize class net.sf.json.JsonConfig 使用json时候将会用到的一个jar包,发现这个包在网上提供的比较少.缺少这个...

    jsonex:Java对象序列化器和反序列化器为JSON格式。 专注于配置友好性,任意对象序列化和紧凑的JSON格式

    如果您也是JSON的拥护者,但讨厌JSON标准的限制,使其很难用作配置格式,但仍然不想将JSON放弃给YAML(JSON很好,为什么需要另一个非常难看的标记语言)。 您可以尝试使用该库。 该库专注于很好地解决以下问题: ...

    JSONConfig:抽象重新配置文件类,交替xml,同时支持json文件

    JSONConfig:抽象重新配置文件类,交替xml,同时支持json文件

    browser-extension-config

    browser-engines.jsonconfig-00000000000.saladict my-ublock-backup.txt桌面my-ublock-mobile.txt安卓tampermonkey-backup.txtuseragent-switcher-preferences.jsonScholarscope_local_data.ssbackupsearch.json....

    JSONObject(net.sf.json)jar包和依赖包

    通过JSONObject json = ... 进入此方法后会继续调用fromObject(Object, JsonConfig)的重载方法,在此重载方法中会通过instanceOf判断待转换的Object对象是否是枚举、注解等类型,这些特殊类型会有特别的判断方法。

    【JSON解析】浅谈JSONObject的使用

    在程序开发过程中,在参数传递,函数返回值等方面,越来越多的使用JSON。JSON(JavaScript Object Notation)是一种轻量级的数据交换格式,同时也易于机器解析和生成、易于理解、阅读和撰写,而且Json采用完全独立于...

Global site tag (gtag.js) - Google Analytics