Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java create JSONObject with empty value as JSONObject

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); or localJson.append(key, new JSONObject());. Each time the value is a JSONArray with the value[0] = null or just [{}]

Is there any way to make it a JSONObject?

like image 294
Mr.Tr33 Avatar asked Oct 16 '25 21:10

Mr.Tr33


1 Answers

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;
}
like image 50
m-szalik Avatar answered Oct 18 '25 13:10

m-szalik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!