How do i append an object to an existing JSON file with Jackson?
File file = new File("test.json");
if (!file.exists()) {
file.createNewFile();
}
ObjectMapper mapper = new ObjectMapper();
ObjectWriter writer = mapper.writer(new DefaultPrettyPrinter());
mapper.writeValue(file, wtf);
In your question, "append" can have multiple meanings/solutions depending in which context you place that word. For example:
Solution of example #1:
// File output: {"name":"Foo","age":20} {"name":"Bar","age":30} {"name":"Baz","age":40}
public static void plainAppendExample() {
File file = new File("u:\\test.json");
ObjectMapper mapper = new ObjectMapper();
try {
JsonGenerator g = mapper.getFactory().createGenerator(new FileOutputStream(file));
mapper.writeValue(g, new Person("Foo", 20));
mapper.writeValue(g, new Person("Bar", 30));
mapper.writeValue(g, new Person("Baz", 40));
g.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Each writeValue() appends to the file a plain JSON object, but ignores the previous JSON structure.
Solution of example #2.1:
// File output: [ {"name" : "Foo", "age" : 20}, {"name" : "Bar", "age" : 30}, {"name" : "Baz", "age" : 40} ]
public static void jsonArrayAppendExample2() {
try {
File file = new File("u:\\test.json");
FileWriter fileWriter = new FileWriter(file, true);
ObjectMapper mapper = new ObjectMapper();
SequenceWriter seqWriter = mapper.writer().writeValuesAsArray(fileWriter);
seqWriter.write(new Person("Foo", 20));
seqWriter.write(new Person("Bar", 30));
seqWriter.write(new Person("Baz", 40));
seqWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Where each write() appends to an existing JSON array in the file, until close() is called.
Solution of example #2.2:
I haven't found a solution for this. In this case, the solution should modify the file by replacing the array closing character ]
and then perform the appends.
Or, if performance and memory is not a problem, you could re-read the JSON file to a Java object, then add a new JSON object, and then write to the file again.
Note: Note that I'm not a Jackson expert, so I don't know if my solution is the best solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With