4

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?

2
  • 3
    Please show a minimal reproducible example rather than just describing what you've tried. Commented Mar 7, 2016 at 15:39
  • Also you should specify which library you're using. Commented Mar 7, 2016 at 15:44

1 Answer 1

3

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;
}
Sign up to request clarification or add additional context in comments.

1 Comment

wow .. thank you ... I hate myself for that. I had this part open and read eatch time JSONObject instead of JSONArray >.>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.