0

I have seen this question and understand the answer, but can not use it in my scenario.

My scenario: I retrieve data via JPA from a mysql database and want to put this data into a JSONObject like this

{
  "A":["1","2","3"], 
  "B":["1","2","3","4"], 
  "C":["1","2"]
}

The problem is I do not know how many arrays I will retrieve. It could be 1 or it could be 200, depending on the data in the database.

If I append the data into a JSONObject like this:

import org.apache.tapestry5.json.JSONObject 
// ...
JSONObject data = new JSONObject();
for (Value val : values) data.append(val.getName(), val.getValue());

I'll get

{"val_name": [[["1"],"2"],"3"], ...}

Is there a way to use JSONOBject.append without creating JSONArrays and puting them into the JSONObject, which will result in a nested JSONObject?

Community
  • 1
  • 1
Martin Grohmann
  • 437
  • 2
  • 17

1 Answers1

1

A JSON object is a "dictionary" -- a map between name and value. A JSON array is a sequential list of values, with only the ordinal position of the value identifying it. It makes no sense to "append" to the object -- you add new name/value pairs to it (although they apparently call it appending, just to confuse you). If, within an object, you want something like "A":["1","2","3"] then you necessarily must insert an array (as the value of a name/value pair) into the object.

But note that either before inserting the array into the object or after you can append additional values to the array. You just need to get/save a reference to the array.

In your above example you're making the mistake of appending to the object rather than the array.

Hot Licks
  • 47,103
  • 17
  • 93
  • 151