如何使用jackson库将pojos附加到json文件中

我是jackson库的新手。我有定期在json文件中写入的数据。我所经历的所有当前教程都覆盖了该文件。

我会使用Jackson库来处理JSON。 ObjectMapper类可以将POJO:s转换为JSON,反之亦然。 除此之外,我将使用java.nio.file.Files类来处理文件写入,如下例所示。

 // First, define some POJO public static class Pojo { private final String content; @JsonCreator public Pojo(String content) { this.content = content; } public String getContent() { return content; } } // This test simply illustrates file writing of JSON objects @Test public void testAppendToFile() throws IOException { // The ObjectMapper is used to convert between Pojos and JSON (and vice versa) final ObjectMapper mapper = new ObjectMapper(); // Convert a Pojo to JSON final String json1 = mapper.writeValueAsString(new Pojo("This is the content #1")); // Write it to the file myfile.json. // The first time the file is created and the content is NOT appended Files.write(new File("myfile.json").toPath(), Arrays.asList(json1), StandardOpenOption.CREATE); // Convert another Pojo to JSON final String json2 = mapper.writeValueAsString(new Pojo("This is the content #2")); // Write to the file again. // The second time the content is appended (due to StandardOpenOption.APPEND) Files.write(new File("myfile.json").toPath(), Arrays.asList(json2), StandardOpenOption.APPEND); // Read the file and verify that there are 2 lines final List lines = Files.readAllLines(new File("myfile.json").toPath()); Assert.assertEquals(2, lines.size()); }