Java:更新JSON文件中嵌套数组节点的值

Java: Update value of nested array node in JSON file

由于项目需要,我必须使用com.fasterxml.jackson.databind库来解析JSON数据不能使用其他可用的JSON库。

我是 JSON 解析的新手,所以不确定这里是否有更好的选择?

我想知道如何更新 JSON 文件中 Array 节点中的字符串值。

以下是示例 JSON。请注意这不是完整的文件内容,它是一个简化版本。

{
  "call": "SimpleAnswer",
  "environment": "prod",
  "question": {
    "assertions": [
      {
        "assertionType": "regex",
        "expectedString": "(.*)world cup(.*)"
      }
    ],
    "questionVariations": [
      {
        "questionList": [
          "when is the next world cup"
        ]
      }
    ]
  }
}

以下是将 JSON 读入 java 对象的代码。

byte[] jsonData = Files.readAllBytes(Paths.get(PATH_TO_JSON));
JsonNode jsonNodeFromFile = mapper.readValue(jsonData, JsonNode.class);

更新根级节点值,例如environmentJSON 文件 中,我在一些 SO 线程上发现了以下方法。

ObjectNode objectNode = (ObjectNode)jsonNodeFromFile;
objectNode.remove("environment");
objectNode.put("environment", "test");
jsonNodeFromFile = (JsonNode)objectNode;
FileWriter file = new FileWriter(PATH_TO_JSON);
file.write(jsonNodeFromFile.toString());
file.flush();
file.close();

问题 1:这是更新 JSON 文件中值的唯一方法吗?它是不是最好的方法?我关心双重转换和文件 I/O 在这里。

问题 2:我找不到更新嵌套数组节点值的方法,例如questionList。将问题从 when is the next world cup 更新为 when is the next soccer world cup

你可以使用ObjectMapper解析那个JSON,使用pojo class解析和更新JSON非常容易JSON。

使用 link 将您的 json 转换为 java class,只需将您的 json 粘贴到此处并下载 class 结构。

您可以使用 访问或更新嵌套的 json 字段。 (点)运算符

ObjectMapper mapper = new ObjectMapper();
    String jsonString="{\"call\":\"SimpleAnswer\",\"environment\":\"prod\",\"question\":{\"assertions\":[{\"assertionType\":\"regex\",\"expectedString\":\"(.*)world cup(.*)\"}],\"questionVariations\":[{\"questionList\":[\"when is the next world cup\"]}]}}";
    TestClass sc=mapper.readValue(jsonString,TestClass.class);

    // to update environment
    sc.setEnvironment("new Environment");
    System.out.println(sc);

    //to update assertionType
    Question que=sc.getQuestion();
    List assertions=que.getAssertions();
    for (int i = 0; i < assertions.size(); i++) {
        Assertion ass= (Assertion) assertions.get(i);
        ass.setAssertionType("New Type");
    }