Java create JSONObject with empty value as JSONObject
14,476
Using org.codehaus.jettison.json.JSONObject:
Use public JSONObject put(String key, Object value)
instead of append
method.
Your code isn't working because method JSONObject append(String key, Object value)
is defined as follows:
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;
}
Author by
Mr.Tr33
Updated on June 04, 2022Comments
-
Mr.Tr33 almost 2 years
I'm trying to create an JSONObject with a specific key and empty value. But the value should be a JSONObject and not a JSONArray.
I already tried it with
localJson.append(key, JSONObject.NULL);
orlocalJson.append(key, new JSONObject());
. Each time the value is a JSONArray with thevalue[0] = null
or just[{}]
Is there any way to make it a JSONObject?
-
Jon Skeet about 8 yearsPlease show a minimal reproducible example rather than just describing what you've tried.
-
Hacketo about 8 yearsAlso you should specify which library you're using.
-
-
Mr.Tr33 about 8 yearswow .. thank you ... I hate myself for that. I had this part open and read eatch time JSONObject instead of JSONArray >.>