Reputation: 25
I am using javax.json library to use Json in Java. I am trying to add JsonObject in JsonArray, for example:
[
{ "some_stuff": "stuff" },
{ "some_stuff": "stuff" }
]
I need to add to this array next object with same keys as in example, but i have frozen atarray.add();
JsonObject jsonObject = Json.createObjectBuilder()
.add("some_stuff", "stuff")
.build();
JsonArray array = jsonReader.readArray();
array.add(jsonObject); // UnsupportedOperationException
Upvotes: 1
Views: 2024
Reputation: 7353
JsonArray is immutable so you cannot add ojects to it (hence the exception). From the docs:
JsonArray represents an immutable JSON array (an ordered sequence of zero or more values). It also provides an unmodifiable list view of the values in the array.
You need to use JsonArrayBuilder
object. Here is at least one way to do that:
Create a JsonArrayBuilder
object. (see the link to the docs for how)
Add each of the elements inside of your JsonArray array =
jsonReader.readArray();
object to the JsonArrayBuilderObject
Add your JsonObject
.
Call .build
on the JsonArrayBuilder
to convert it to a JsonArray
that will contain all of the elements.
Upvotes: 2