0

This is "test.json" before I run my code:

{
  "example1": {
    "example2": {
      "example3": 30
    }
  }
}

When I run this code:

public static void test() throws IOException {

    Path fileName = Paths.get("src/test.json");

    try (BufferedReader reader = Files.newBufferedReader(fileName);
        BufferedWriter writer = Files.newBufferedWriter(fileName, StandardOpenOption.WRITE)) {
        Gson gson = new GsonBuilder().setPrettyPrinting().create();
        JsonObject value = gson.fromJson(reader, JsonObject.class);

        JsonObject object1 = new JsonObject();
        JsonObject object2 = new JsonObject();

        value.add("example1", object1);
        object1.add("example2", object2);
        object2.addProperty("example4", 40);

        gson.toJson(value, writer);

    }
    
}

Then this happens to "test.json":

{
  "example1": {
    "example2": {
      "example4": 40
    }
  }
}

How can I add the data from "example4" to "example2" without removing "example3"?

0 Answers0