GogoManTV
GogoManTV

Reputation: 25

Json: Add object to array

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

Answers (1)

jlars62
jlars62

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:

  1. Create a JsonArrayBuilder object. (see the link to the docs for how)

  2. Add each of the elements inside of your JsonArray array = jsonReader.readArray(); object to the JsonArrayBuilderObject

  3. Add your JsonObject.

  4. Call .build on the JsonArrayBuilder to convert it to a JsonArray that will contain all of the elements.

Upvotes: 2

Related Questions