2

Following code produces a nested array as a result for keys containing three items:

import org.codehaus.jettison.json.JSONObject;
// ...

JSONObject ret = new JSONObject();
for (Key key:keys) ret.append("blocked",key.id());

The result is:

{"blocked": [[["1"],"2"],"3"]}

Is this expected? If it is, how can I construct a plain array adding item by item?

Suma
  • 33,181
  • 16
  • 123
  • 191

3 Answers3

9

You need to create a JSONArray object:

JSONObject ret = new JSONObject();
JSONArray arr = new JSONArray();
arr.put("1");
arr.put("2");
arr.put("3");
ret.put("blocked", arr);

The result is:

{"blocked":["1","2","3"]}
legege
  • 421
  • 4
  • 12
3

It's curious because the API says the following:

Append values to the array under a key. If the key does not exist in the JSONObject, then the key is put in the JSONObject with its value being a JSONArray containing the value parameter. If the key was already associated with a JSONArray, then the value parameter is appended to it.

But it doesn't work correctly. When I do:

JSONObject o = new JSONObject();
o.append("arr", "123");
o.append("arr", "456");

I get an Exception saying that "JSONObject[arr] is not a JSONArray". It looks like there is a bug.

Suma
  • 33,181
  • 16
  • 123
  • 191
Thomas
  • 31
  • 1
0

I ran into a similar problem. You should use the put method; not the append method. And, of course, you should create a JSONArrray and use that as the second argument of the put method.

buttonius
  • 39
  • 3