首先,分别运行下面两段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); /* */ }