更新 Java 中嵌套 JSON 的值

Update value of a nested JSON in Java

我必须处理以下预定义的 JSON 请求。此 JSON 存储在本地文件中。我想更新 JSON 中几个元素("level-4b-1" 和 "level-4b-3" > "StartDate")的值并提交请求。


{
"level-1": {
  "level-2": {
     "level-3": {
        "level-4a": [
           "value-4a"
        ],
        "level-4b": [
           {
              "level-4b-1": "value-4b-1",
              "level-4b-2": "value-4b-2",
              "level-4b-3": {
                 "StartDate": "2017-11-13T00:00:00"
              }
           }
        ]
     },
     ...

我有以下代码,但我不确定如何深入一行代码然后更新值。

    JSONParser parser = new JSONParser();
    Object requestFileObj = parser.parse(new FileReader(context.getRealPath(localJsonFile)));
    JSONObject requestJsonObject =  (JSONObject) requestFileObj;

    if (requestJsonObject instanceof JSONObject) {

        JSONObject level1 = (JSONObject)chartRequestJsonObject.get("level-1");

JsonPath 提供了一种方便的方法来寻址 json 文档中的节点。 JayWay 是一个很好的 java 实现。

与 JayWay 一起:

DocumentContext doc = JsonPath.parse(json);
doc.set("level-1.level-2.level-3.level-4b[0].level-4b-3.StartDate", Instant.now().toString());
System.out.println(doc.jsonString());

如果您愿意使用 Google 的 JSON 库 (https://github.com/google/gson),您可以更新嵌套元素并保存它们,如以下示例代码所示:

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonObject;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.io.IOException;
import java.io.FileReader;
import java.nio.file.StandardOpenOption;

public class JsonUpdater {
  // Method to update nested json elements
  public void updateJson(String inputFile, String outputFile) {
      try {
          // Get the json content from input file
          String content = new String(Files.readAllBytes(Paths.get(inputFile)));

          // Get to the nested json object
          JsonObject jsonObj = new Gson().fromJson(content, JsonObject.class);
          JsonObject nestedJsonObj = jsonObj
                  .getAsJsonObject("level-1")
                  .getAsJsonObject("level-2")
                  .getAsJsonObject("level-3")
                  .getAsJsonArray("level-4b").get(0).getAsJsonObject();

          // Update values
          nestedJsonObj.addProperty("level-4b-1", "new-value-4b-1");
          nestedJsonObj.getAsJsonObject("level-4b-3").addProperty("StartDate", "newdate");

          // Write updated json to output file
          Files.write(Paths.get(outputFile), jsonObj.toString().getBytes(), StandardOpenOption.CREATE);
      } catch (IOException exception) {
          System.out.println(exception.getMessage());
      }
  }

  // Main
  public static void main(String[] args) {
    JsonUpdater jsonUpdater = new JsonUpdater();
    jsonUpdater.updateJson("test.json", "new.json");
  }
}

以上代码从 test.json 中读取 json 字符串,更新 level-4b-1StartDate 的值(在 level-4b-3 内),并保存更新后的值json 字符串变成 new.json