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

0 java json jackson

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

was*_*ren 5

我会使用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<String> lines = Files.readAllLines(new File("myfile.json").toPath());
    Assert.assertEquals(2, lines.size());
}
Run Code Online (Sandbox Code Playgroud)