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.

有帮助吗?

解决方案

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.

其他提示

You can't simply "append". In the general case you must read in the JSON, modify the tree-structured memory image, then "serialize" it back to linear JSON.

In very simple cases such as the above you could in theory seek to the end, backspace over the closing ], then write out ,, the second object, and a new closing ], but it's not a general solution to updating JSON.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top