json-jsonConfig使用
一,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
}
二,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安全问题。
本文转载
json-jsonConfig使用的更多相关文章
- 使用JsonConfig控制JSON lib序列化
将对象转换成字符串,是非常常用的功能,尤其在WEB应用中,使用 JSON lib 能够便捷地完成这项工作.JSON lib能够将Java对象转成json格式的字符串,也可以将Java对象转换成xml格 ...
- Java中json的构造和解析
什么是 Json? JSON(JvaScript Object Notation)(官网网站:http://www.json.org/)是 一种轻量级的数据交换格式. 易于人阅读和编写.同时也易于机 ...
- net.sf.json.JSONException: There is a cycle in the hierarchy!的解决办法
使用Hibernate manytoone属性关联主表的时候,如果使用JSONArray把pojo对象转换成json对象时,很容易出现循环的异常.解决的办法就是, 在转换json对象时忽略manyto ...
- json、javaBean、xml互转的几种工具介绍
json.javaBean.xml互转的几种工具介绍 转载至:http://blog.csdn.net/sdyy321/article/details/7024236 工作中经常要用到Json.Jav ...
- Json与javaBean之间的转换工具类
/** * Json与javaBean之间的转换工具类 * * {@code 现使用json-lib组件实现 * 需要 * json-lib-2.4-jdk15.jar * ...
- Json与Bean互转,Timestamp类型的问题
Json与Java Bean互相转换时,Bean中的Timestamp字段是无法直接处理的,需要实现两个转换器. DateJsonValueProcessor的作用是Bean转换为Json时将Time ...
- 日志——JSON的相关方法
http://www.cnblogs.com/henryxu/archive/2013/03/10/2952738.html JSON jar包: commons-lang.jar commons- ...
- json:There is a cycle in the hierarchy!
在使用JSONObject.fromObject的时候,出现“There is a cycle in the hierarchy”异常. 意思是出现了死循环,也就是Model之间有循环包含关系: 解决 ...
- 扩展struts2的结果集StrutsResultSupport 自定义Result处理JSON
以前在采用Struts2开发的项目中,对JSON的处理一直都在Action里处理的,在Action中直接Response,最近研读了一下Struts2的源码,发现了一个更加优雅的解决办法,自己定义一个 ...
- json转换对象 对象属性首字母为大写会出错 可以用以下方法
package open_exe; import net.sf.json.JSONObject; import net.sf.json.JsonConfig; import net.sf.json.u ...
随机推荐
- Eclipse的 JSON Edit插件
1. Json-Eclipse-Plugin https://github.com/boothen/Json-Eclipse-Plugin 2. 另外一个JSON Edit工具 https://tfe ...
- 使用Access-Control-Allow-Origin解决跨域
什么是跨域 当两个域具有相同的协议(如http), 相同的端口(如80),相同的host(如www.google.com),那么我们就可以认为它们是相同的域(协议,域名,端口都必须相同). 跨域就指着 ...
- jQuery语法
目录: 一.选择网页元素二.改变结果集三.链式操作四.元素的操作五.元素的操作:移动六.元素的操作:复制.删除和创建七.工具方法八.事件操作九.特殊效果 一.选择网页元素这也是jQuery的基本设计思 ...
- HTML5+jquery整屏页面切换效果
压缩包下载 演示地址 http://www.yyyweb.com/demo/page-transitions/
- wechat开发
1.easywechat安装 2.weichat打通服务器 function getTest(Request $request){ $token = 'zhenhaokeji'; $data = $r ...
- XAMPP中proftpd的简明配置方法
XAMPP中proftpd的简明配置方法 用LAMPP的安装方法可以开一个默认的nobody用户,用lampp security就可以初始设置相应的默认用户密码.如果要有多用户,又怎样管理.目录怎 ...
- Nginx 启用 https
在nginx.conf中增加新server配置 server { listen ; server_name www.some.com; ssl on; ssl_certificate sslkey/s ...
- Windows Server 2008 R2中的ASP.NET环境架设
.NET Framework的部分功能在Windows Server 2008 R2得到支持,包括:.NET 2/3/3.5的子集和ASP.NET.另外,PowerShell也在Server Core ...
- 架设ftp反向代理服务器
因网络环境限制,需要从内网(不能直接连通外网)向外部的ftp上传.下载文件,只能在网关服务器上架设ftp反向代理(网关服务器可同时连通外网与内网,但是不允许内部应用部署在这台机器上). 试了几个方案: ...
- TinyFrame升级之一:框架概览
由于之前的TinyFrame多于简单,并且只是说明原理,并无成型的框架出来,所以这次我把之前的知识进行了汇总,然后做出了这一版的TinyFrame框架. 整个框架的结构如下: TinyFrame.Da ...