Creating JSON in java using org.json
Asked Answered
K

2

9

I am trying to create a json string in java using org.json library and following is the code snippet.

JSONArray jSONArray = new JSONArray();
JSONObject jSONObject = new JSONObject();
jSONObject.accumulate("test", jSONArray);
System.out.println(jSONObject.toString());

I expected it to print

{"test":[]} 

while it prints

{"test":[[]]}
Kistner answered 29/4, 2013 at 5:30 Comment(1)
Here's a short video that demonstrates creating a JSONObject using org.json. youtube.com/watch?v=-qEpxIARKxETerrel
C
10

instead of using accumulate use put this way it won;t add it to a pre-existing (or create and add) JSONArray, but add it as a key to the JSONObject like this:

JSONArray array = new JSONArray();
JSONObject obj = new JSONObject();
obj.put("test", array);
System.out.println(obj.toString());

and now it'll print {"test":[]}

Chaise answered 29/4, 2013 at 5:37 Comment(0)
C
4

That is because in the accumulate method,

Object object = this.opt(key); //gets the key value. Null in your case.
if (object == null) {
    this.put(key,
        value instanceof JSONArray ? new JSONArray().put(value) : value);
}

This is as per the API which clearly says (for the accumulate method) -

Accumulate values under a key. It is similar to the put method except that if there is already an object stored under the key then a JSONArray is stored under the key to hold all of the accumulated values. If there is already a JSONArray, then the new value is appended to it. In contrast, the put method replaces the previous value. If only one value is accumulated that is not a JSONArray, then the result will be the same as using put. But if multiple values are accumulated, then the result will be like append.

You can use put() as mentioned in the other answer, for your desired result.

Commodity answered 29/4, 2013 at 5:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.