首先,分別運行下面兩段json和fastjson的代碼:java
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
// 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()源碼:this
// 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); /* */ }