json-lib 之jsonConfig具体应用
一,setCycleDetectionStrategy 防止自包含
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.Object(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) JSerializer.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.Object(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.Object(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.Object(null) 这个参数直接传null进去,json-lib会怎么处理惩罚
public static JSONObject Object( Object object, JsonConfig jsonConfig ) {
if( object == null || JSONUtils.isNull( object ) ){
return new JSONObject( true );
看代码是直接返回了一个空的JSONObject,没有效到任何默认值输出。
B,其次,我们看若是java对象直接是一个JDK中已经有的类(什么指Enum,Annotation,JSONObject,DynaBean,JSONTokener,JString,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 _JSONObject( (JSONObject) object, jsonConfig );
}else if( object instanceof DynaBean ){
return _DynaBean( (DynaBean) object, jsonConfig );
}else if( object instanceof JSONTokener ){
return _JSONTokener( (JSONTokener) object, jsonConfig );
}else if( object instanceof JString ){
return _JString( (JString) object, jsonConfig );
}else if( object instanceof Map ){
return _Map( (Map) object, jsonConfig );
}else if( object instanceof String ){
return _String( (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{
按照以上代码,首要发明_Map是不支撑应用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 );
}
}
……
按照我的注释, 上方的代码显然是存在抵触。
_DynaBean是支撑DefaultValueProcessor的和下面的C是一样的。
C,我们看若是 java 对象是自定义类型的,并且里面的属性包含空值(没赋值,默认是null)也就是上方B还没贴出来的最后一个else
else {return _Bean( 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.Object(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) JSerializer.toJSON(jsonString,config);
System.out.println(json);
}
========================== JSON 输出的安然题目 ===============
我们做法度的时辰主如果应用 Java To Json的体式格式,下面描述的是 安然性题目:
@SuppressWarnings("unchecked")
public static void testSecurity() {
Map map = new HashMap();
map.put(""} {", "");
JSONObject jsonObject = JSONObject.Object(map);
System.out.println(jsonObject);
}
public static void main(String[] args) {
JsonTest.testSecurity();
}
输出的内容:
{""} {":"" }
若是把这段内容直接贴到记事本里面,定名为 testSecu.html ,然后用浏览器打开辟明履行了此中的 js脚本。如许就轻易产生XSS安然题目。
json-lib 之jsonConfig具体应用的更多相关文章
- JSON lib 里JsonConfig详解
一,setCycleDetectionStrategy 防止自包含 /** * 这里测试如果含有自包含的时候需要CycleDetectionStrategy */ public static void ...
- 使用JsonConfig控制JSON lib序列化
将对象转换成字符串,是非常常用的功能,尤其在WEB应用中,使用 JSON lib 能够便捷地完成这项工作.JSON lib能够将Java对象转成json格式的字符串,也可以将Java对象转换成xml格 ...
- Json lib集成stucts2的使用方法 抛出 NestableRuntimeException异常的解决办法
首先贴出struts 2.3.16需要导入的包 因为使用的是2.3 版本,必须要导入这个包,否则会报java.lang.NoClassDefFoundError: org/apache/commons ...
- Atitit.json类库的设计与实现 ati json lib
Atitit.json类库的设计与实现 ati json lib 1. 目前jsonlib库可能有问题,可能版本冲突,抛出ex1 2. 解决之道:1 2.1. 自定义json解析库,使用多个复合的js ...
- json lib 2.4及其依赖包下载
下载文件地址:https://files.cnblogs.com/files/xiandedanteng/json-lib-2.4%26dependencies_jars.rar 它包括 common ...
- Json的JsonValueProcessor方法
将对象转换成字符串,是非常常用的功能,尤其在WEB应用中,使用 JSON lib 能够便捷地完成这项工作. JSON lib能够将Java对象转成json格式的字符串,也可以将Java对象转换成xml ...
- java集合转换成json时问题和解决方法
json+hibernate死循环问题的一点见解,有需要的朋友可以参考下. [问题]如题所示,在我们使用hibernate框架而又需要将对象转化为json的时候,如果配置了双向的关联关系,就会出现这个 ...
- java使用json-lib库的json工具类.
import net.sf.ezmorph.object.DateMorpher;import net.sf.json.JSONArray;import net.sf.json.JSONObject; ...
- JSON — Java与JSON数据互转
转换时Bean所要求的: 被转换的Bean必需是public的. Bean被转换的属性一定要有对应的get方法,且一定要是public的. Bean中不能用引用自身的this的属性,否则运行时出现et ...
- java中Array/List/Map/Object与Json互相转换详解
http://blog.csdn.net/xiaomu709421487/article/details/51456705 JSON(JavaScript Object Notation): 是一种轻 ...
随机推荐
- BZOJ3867 : Nice boat
每个点最多被修改$O(\log n)$次,线段树记录区间最值暴力更新. #include<cstdio> #define N 262145 int T,n,m,i,op,c,d,p,s[N ...
- COJ968 WZJ的数据结构(负三十二)
WZJ的数据结构(负三十二) 难度级别:D: 运行时间限制:5000ms: 运行空间限制:262144KB: 代码长度限制:2000000B 试题描述 给你一棵N个点的无根树,边上均有权值,每个点上有 ...
- jQuery加载外部文件的方式get、post、ajax、load的区别及异步加载的实现
一.$.post(url, [data], [callback], [type]) url (String) : 发送请求的URL地址. data (Map) : (可选) 要发送给服务器的数据,以 ...
- Struts2+Spring3+Mybatis3开发环境搭建
本文主要介绍Struts2+Spring3+Mybatis3开发环境搭建 Struts和Spring不过多介绍. MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架.MyBa ...
- hdu 饭卡
本题的思路是:首先如果m<5,直接输出:若m>5,则先拿出5元钱买最贵的东西,这样背包容量就变成了m-5,商品数量为n-1的0/1背包问题. 此题的状态转移方程为:dp[j]=max{dp ...
- CVE-2013-3908 Internet Explorer打印预览功能可导致信息泄露
原文:http://masatokinugawa.l0.cm/2014/11/ie-printpreview-infoleak.html 问题1: 在IE9和以前的版本当中进行打印预览操作时,IE会取 ...
- CVE-2014-4113 windows通杀本地提权0day
这个0day的发现挺有意思的,是老外CrowdStrike 发现的,被老外监测程序发现显示从WEBSHELL使用Win64.exe来提升权限. 原文地址:http://blog.crowdstrike ...
- Asp.Net 常用代码-备用
1.DropDownList 复制 //DropDownList DropDownList2.Items.Clear(); foreach (ListItem li in DropDownList1. ...
- 【新产品发布】【iCore2 ARM / FPGA 双核心板】
iCore2是一款包含ARM / FPGA两大利器的双核心板.ARM方面,采用意法半导体高性能的32位Cortex-M3内核STM32F103VE微处理器,主频达72MHz,并包含丰富外设接口.FPG ...
- STATIC::含义
Static 关键字,是作为作用域引用,类似Parent和self 关键字,和Parent和 Self不同 Parent引用父类作用域 Self 引用当前类作用域 Static 引用全部静态作用于,子 ...