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


免責聲明!

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



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