3

I read a JSON array from a file but I'd like to add additional entries into the array. How would I go about doing this using the javax.json library?

private String getJson(FileInputStream fis) throws IOException {
    JsonReader jsonReader = Json.createReader(fis);
    // Place where I'd like to get more entries.

    String temp = jsonReader.readArray().toString();
    jsonReader.close();
    fis.close();
    return temp;
}

Preview of the JSON format of the file:

[
    {"imgOne": "test2.png", "imgTwo": "test1.png", "score": 123123.1},
    {"imgOne": "test2.png", "imgTwo": "test1.png", "score": 1234533.1}
]

1 Answer 1

2

The short answer is that you can't. JsonArray (and the other value types) is meant to be immutable. The javadoc 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.

The long answer is to create a new JsonArray object by copying over the values from the old one and whatever new values you need.

For example

// Place where I'd like to get more entries.
JsonArray oldArray = jsonReader.readArray();
// new array builder
JsonArrayBuilder builder = Json.createArrayBuilder();
// copy over old values
for (JsonValue value : oldArray) {
    builder.add(value);
}
// add new values
builder.add("new string value");
// done
JsonArray newArray = builder.build();
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.