Jackson 不会将新的 JSON 对象附加到现有的 Json 文件

Jackson doesn't append new JSON object to exisiting Json file

我正在尝试构建一个 Springboot 应用程序,它允许从 Postman 插入 Json 对象并将其保存到具有其他数据的现有 json 文件中。我是 Jackson 的新手,也许我错过了什么?

这是我的 json 文件的样子:

[
   {
      "Name":"After Dark",
      "Author":"Haruki Murakami"
   },
   {
      "Name":"It",
      "Author":"Stephen King"
   }
]

这是我试过的:

@PostMapping("/insertBook")
public void insertBook(@RequestBody Book book)  {
    File booksJsonFile = Paths.get(this.getClass().getResource("/books.json").toURI()).toFile();
    objectMapper.writeValue(booksJsonFile, book);
}

它插入到一个空文件,但它不会附加到现有的 json 文件。

我也试过这个:

@PostMapping("/insertBook")
public void insertBook(@RequestBody Book book) throws URISyntaxException {

    try {
        File file = Paths.get(this.getClass().getResource("/books.json").toURI()).toFile();
        FileWriter fileWriter = new FileWriter(file, true);
        SequenceWriter seqWriter = objectMapper.writer().writeValuesAsArray(fileWriter);
        seqWriter.write(book);

        seqWriter.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这是我从 Postman 发送的内容:

我是否需要使用其他东西来达到我想要的结果? 我会感谢你的帮助。

我已经尝试根据您的代码重现您的问题,得出以下结论:

  1. 不能直接修改resources下的文件。这里是 .

  2. 我设法将新的 JSON 附加到文件(使用您的方法,但在本地保存文件),但这可能不是您所期望的(json 结构已损坏):

[
   {
      "Name":"After Dark",
      "Author":"Haruki Murakami"
   },
   {
      "Name":"It",
      "Author":"Stephen King"
   }
][{"Name":"new name","Author":"new author"}]

恐怕无法直接在文件中更新当前 JSON 结构。

  1. 我使用 org.json library 设法解决了您的问题。但是,我的解决方案的缺点是每次都需要重写整个文件。此外,我使用了 synchronized 关键字以避免同时修改文件。
public synchronized void updateJsonFile(Book book) throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    Path path = Paths.get("./books.json");
    final String currentJsonArrayAsString = Files.readString(path);

    try (FileWriter fileWriter = new FileWriter(path.toFile(), false)) {

        JSONObject jsonObject = new JSONObject(objectMapper.writeValueAsString(book));
        JSONArray jsonArray = new JSONArray(currentJsonArrayAsString);
        jsonArray.put(jsonObject);

        fileWriter.write(jsonArray.toString());
    }
}

现在 books.json 有以下内容:

[
   {
      "Author":"Haruki Murakami",
      "Name":"After Dark"
   },
   {
      "Author":"Stephen King",
      "Name":"It"
   },
   {
      "Author":"new author",
      "Name":"new name"
   }
]