0

I have to work with the following pre-defined JSON request. This JSON is stored in a local file. I would like to update the values of a couple of elements ("level-4b-1" and "level-4b-3" > "StartDate") in the JSON and submit the request.


{
"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"
              }
           }
        ]
     },
     ...

I have the following code but I am not sure how to go deeper in a single line of code and then update the value.

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

2 Answers 2

4

JsonPath provides a convenient way of addressing nodes in json documents. JayWay is a good java implementation.

With 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());
Sign up to request clarification or add additional context in comments.

1 Comment

How did you managed to make it work? Tried your code but it's not working. final Configuration configuration = Configuration.defaultConfiguration() .addOptions(Option.DEFAULT_PATH_LEAF_TO_NULL) .addOptions(Option.SUPPRESS_EXCEPTIONS); DocumentContext doc = JsonPath.parse("{}", configuration); doc.set("level-1.level-2.level-3.level-4b[0].level-4b-3.StartDate", Instant.now().toString()); System.out.println(doc.jsonString());
2

If you are open to using Google's JSON library (https://github.com/google/gson), you can update nested elements and save them as shown in the following sample code:

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

The above code reads json string from test.json, updates the values for level-4b-1 and StartDate (within level-4b-3), and saves the updated json string into new.json.

1 Comment

This is by far an amazing solution! I was able to update some values of a JSON following this code. thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.