문제

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