问题
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