一,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安全問題。