我是杰克逊图书馆的新手。我已定期在json文件中写入数据。我所经历的所有当前教程都会覆盖该文件。
答案 0 :(得分:4)
我会使用Jackson library来处理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());
}