【问题标题】:Java: Update value of nested array node in JSON fileJava:更新 JSON 文件中嵌套数组节点的值
【发布时间】:2017-05-27 04:07:27
【问题描述】:

由于项目需要,我必须使用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

【问题讨论】:

    标签: java arrays json jackson jackson-databind


    【解决方案1】:

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

    使用link 将您的json 转换为java 类,只需在此处粘贴您的json n 下载类结构。

    您可以使用 . (点)运算符

    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");
        }
    

    【讨论】:

    • 工作就像一个魅力。不再需要处理 JSON 层次结构。我可以轻松地解析与 java 对象和文件之间的数据,更新属性并将其写回文件。 #1) 读取数据到java对象:TestClass testClass = mapper.readValue(new File(FILE_FULL_PATH), TestClass.class); #2) 按照 Pranay 的建议更新 java 对象 #3 将对象写回文件:mapper.writeValue(new File(FILE_FULL_PATH), testClass);
    猜你喜欢
    • 1970-01-01
    • 2022-06-13
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-25
    • 1970-01-01
    • 2021-02-24
    相关资源
    最近更新 更多