JSONObject與null

前言

今天在寫代碼的時候發現在 JSON 中 由於put了key對應的value爲null,結果這個JSON鍵值對沒有輸出

org.json.JSONObject

在orgJSON 中,如果直接put value會有報錯提示:

org.json.JSONObject orgJSON = new org.json.JSONObject();
// IDE提示The method put(String, Collection) is ambiguous for the type JSONObject
orgJSON.put("null", null);

但是,org.json.JSONObject 提供了一個JOSNObject.NULL

orgJSON.put("JSONObject.NULL", org.json.JSONObject.NULL);
System.out.println("JSONObject.NULL : "+orgJSON);

// 控制檯輸出
JSONObject.NULL : {"JSONObject.NULL":null}
System.out.println(JSONObject.NULL == null);
// 控制檯
false

通過查閱org.json.JSONObject的文檔,發現文檔是這樣說的

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONObject.NULL object.

參考文檔:https://stleary.github.io/JSON-java/org/json/JSONObject.html

net.sf.json.JSONObjcet

net.sf.json.JSONObject netJSON = new net.sf.json.JSONObject();
netJSON.put("null", null);
System.out.println("netJSON" + netJSON); 
// 控制檯輸出 : 
netJSON{}

文檔中這樣寫的:

The values can be any of these types: Boolean, JSONArray, JSONObject, Number, String, or the JSONNull object.

但是吧

// IDE提示:net.sf.json.JSONNull cannot be resolved to a variable
netJSON.put("JSONNull", net.sf.json.JSONNull);

參考文檔:http://json-lib.sourceforge.net/apidocs/jdk15/net/sf/json/JSONObject.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章