Reputation: 3
I have a problem with the json-lib library for java, it turns out that if the JSON that I get only one record I have not added the [], but if you have more than one record if I add them.
This is my code that comes from a SQL query:
while (oResultSet.next()) {
JSONObject list = new JSONObject();
list.accumulate("nombre", oResultSet.getString("nombre"));
list.accumulate("goles", oResultSet.getInt("goles"));
json.accumulate("list", list);
}
return json;
An example of what brings me back if you have more than one record
{"list":[{"nombre":"Josele","goles":5},{"nombre":"Edu","goles":4}]}
And now an example with a single record
{"list":{"nombre":"Eduard","goles":2}}
As you can see he lacks the [], and I would like to also appear as manerjar when I create the json failures.
I wish that when I have a single record also appeared to me the [ ]
Thanks for the attention
Upvotes: 0
Views: 86
Reputation: 76918
The answer is: Don't use .accumulate()
as that's exactly what it does.
Explicitly create and add a JSONArray
to your json
object prior to your loop. Inside your loop, retrieve it and add to it:
JSONObject json = new JSONObject();
json.put("list", new JSONArray());
...
while (oResultSet.next()) {
JSONObject obj = new JSONObject();
obj.accumulate("nombre", oResultSet.getString("nombre"));
obj.accumulate("goles", oResultSet.getInt("goles"));
json.getJSONArray("list").add(obj);
}
Upvotes: 0