1

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
8
  • I don't think you will succeed in that unless you serialize the object you want to add. tutorialspoint.com/java/java_serialization.htm Commented Nov 10, 2014 at 18:12
  • how do you initialize your Json Reader ? Commented Nov 10, 2014 at 18:13
  • @OzanTabak Yes. This is just example. Commented Nov 10, 2014 at 18:14
  • And I am using javax.json library. Commented Nov 10, 2014 at 18:16
  • javax.json is one of the worst JSON kits for Java. There are about a dozen others. Commented Nov 10, 2014 at 18:16

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.