Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change JsonObject in JsonArray?

Tags:

java

json

I'm using javax.json and when I tried change jsonObject in my jsonArray:

String jsonString = "[{\"name\":\"xyz\"," +
                        "\"URL\":\"http://example.com\"}]";
JsonReader jsonReader = Json.createReader(new StringReader(jsonString));
JsonArray jsonArray = jsonReader.readArray();

String jsonNewString = "{\"name\":\"zyx\","
                         + "\"URL\":\"http://example2.com\"}]";   
jsonReader = Json.createReader(new StringReader(jsonNewString));
JsonObject jsonObject = jsonReader.readObject();
jsonReader.close();

jsonArray.remove(0);
jsonArray.add(0, jsonObject);

I got this exception:

java.lang.UnsupportedOperationException
at java.util.AbstractList.remove(AbstractList.java:161)

I also tried: jsonArray.set(0, jsonObject);, and got the same UnsupportedOperationException.

like image 403
Alchemik123 Avatar asked Jun 10 '26 23:06

Alchemik123


1 Answers

The javadoc of JsonArray states

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 can't change it. Create a new one with the value(s) you want.

like image 137
Sotirios Delimanolis Avatar answered Jun 12 '26 11:06

Sotirios Delimanolis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!