Yann Le Moigne Yann Le Moigne - 15 days ago 9
Java Question

How to append object to a json file with JSR 353 (Java API for JSON Processing)

Using JSR-353 (https://jsonp.java.net/index.html)
I would like to open a json file and append some object in the root array, eg :

[{"foo":"bar"}]


I would like with a code about like this :

try(JsonGenerator writer = Json.createGenerator(new FileOutputStream(this.file))){
writer.writeStartObject().write("hello", "world").writeEnd();
} catch (IOException e) {
e.printStackTrace();
}


And obtain in the end :

[
{"foo":"bar"},
{"hello":"world"}
]


Note : I don't want to have to load the full json in-memory to append my data.

Answer

Note : I don't want to have to load the full json in-memory to append my data.

Basically, you can't. You would have to parse the full data structure, so that your write(..) would know where to write. Otherwise, it's just appending somewhere and that might break the JSON format.

So read the JSON from the file, generate a JsonArray from it. Create a new JsonObject from your values. Add it to the array. Then write the full array.