Using javax/json, how can I add elements to an existing JsonArray?

笑着哭i 提交于 2021-01-28 22:49:58

问题


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:


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();


来源:https://stackoverflow.com/questions/36918042/using-javax-json-how-can-i-add-elements-to-an-existing-jsonarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!