[英]How to create JsonArray and JsonObject in JsonObject java
[英]Java create JSONObject with empty value as JSONObject
我正在嘗試創建具有特定鍵和空值的JSONObject。 但是該值應該是JSONObject,而不是JSONArray。
我已經嘗試過使用localJson.append(key, JSONObject.NULL);
或localJson.append(key, new JSONObject());
。 每次該值是一個JSONArray,其value[0] = null
或僅是[{}]
有什么辦法可以使其成為JSONObject嗎?
使用org.codehaus.jettison.json.JSONObject :
使用public JSONObject put(String key, Object value)
代替append
方法。
您的代碼無法正常工作,因為方法JSONObject append(String key, Object value)
的定義如下:
public JSONObject append(String key, Object value) throws JSONException {
testValidity(value);
Object o = opt(key);
if (o == null) {
put(key, new JSONArray().put(value));
} else if (!(o instanceof JSONArray)){
throw new JSONException("JSONObject[" + key + "] is not a JSONArray.");
} else {
put(key, new JSONArray().put(o).put(value));
}
return this;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.