比較json和fastjson的put()


首先,分別運行下面兩段json和fastjson的代碼:

import org.json.JSONException;
import org.json.JSONObject;

public class Jsons {
	public static void main(String[] args) throws JSONException {
		JSONObject jsons = new JSONObject();
		jsons.put("key","123");
		
		System.out.println("#1:"+ jsons.toString());
		System.out.println("#2:"+ new JSONObject().put("key", "123").toString());
	}
}
import com.alibaba.fastjson.JSONObject;

public class FastJsons {
	public static void main(String[] args) {
		JSONObject fastJsons = new JSONObject();
		fastJsons.put("kye", "456");
		
		System.out.println("#1:" + fastJsons.toString());
		System.out.println("#2:" + new JSONObject().put("key:", "456").toString() );
	}
	
}

觀察兩個類,貌似沒有什么區別,但是運行之后,控制台打印的結果卻是:

// json
#1:{"key":"123"}
#2:{"key":"123"}
// fastjson
#1:{"kye":"456"}
Exception in thread "main" java.lang.NullPointerException
	at day1.FastJsons.main(FastJsons.java:11)

我們發現fastjson中報了異常,然后我們來查看各自put()源碼:

// json
/*      */   public JSONObject put(String key, Object value)
/*      */     throws JSONException
/*      */   {
/* 1069 */     if (key == null) {
/* 1070 */       throw new JSONException("Null key.");
/*      */     }
/* 1072 */     if (value != null) {
/* 1073 */       testValidity(value);
/* 1074 */       map.put(key, value);
/*      */     } else {
/* 1076 */       remove(key);
/*      */     }
/* 1078 */     return this;
/*      */   }
// fastjson
/*     */   public Object put(String key, Object value) {
/* 316 */     return map.put(key, value);
/*     */   }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM