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;
}
Share:
14,476
Mr.Tr33
Author by

Mr.Tr33

Updated on June 04, 2022

Comments

  • Mr.Tr33
    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); 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?

    • Jon Skeet
      Jon Skeet about 8 years
      Please show a minimal reproducible example rather than just describing what you've tried.
    • Hacketo
      Hacketo about 8 years
      Also you should specify which library you're using.
  • Mr.Tr33
    Mr.Tr33 about 8 years
    wow .. thank you ... I hate myself for that. I had this part open and read eatch time JSONObject instead of JSONArray >.>