原生的Json在封裝的時候,如果value為空的話,則不會添加這條鍵值對,想實現如果value為空的話也記錄下來。像這種(key:null)。
于是找到Json源碼中的put方法,看到在put的時候有一個判斷,如果value是空的話,則remove了key。把這條代碼注釋一下就好了。
貼上原JSON代碼
/**
* Put a key/value pair in the JSONObject. If the value is null, then the
* key will be removed from the JSONObject if it is present.
*
* @param key
* A key string.
* @param value
* An object which is the value. It should be of one of these
* types: Boolean, Double, Integer, JSONArray, JSONObject, Long,
* String, or the JSONObject.NULL object.
* @return this.
* @throws JSONException
* If the value is non-finite number or if the key is null.
*/
public JSONObject put(String key, Object value) throws JSONException {
if (key == null) {
throw new NullPointerException("Null key.");
}
if (value != null) {
testValidity(value);
this.map.put(key, value);
} else {
this.remove(key);
}
return this;
}
在使用Json封裝的時候,比如我先put的是一條key為"b"的記錄,然后再put一條key為"a"的記錄,最后打印的字符串是"a"的記錄在前,"b"的記錄在后。想實現按記錄順序來排列,于是查看Json代碼。
發(fā)現在Json實例的時候創(chuàng)建的是HashMap對象
/**
* Construct an empty JSONObject.
*/
public JSONObject() {
this.map = new HashMap<String, Object>();
}
然而HashMap會默認將key以hash碼來進行排序的。
于是又默默的改了句代碼。。。
將HashMap改成了LinkedHashMap
/**
* Construct an empty JSONObject
*/
public JSONObject() {
this.map = new LinkedHashMap<String,Object>();
}
<a >加個修改后的源碼與成品鏈接</a>