rumit patel
rumit patel

Reputation: 1951

Java: Update value of nested array node in JSON file

Because of the project requirement, I have to use com.fasterxml.jackson.databind library to parse JSON data cannot use other JSON libraries available.

I am new to JSON parsing, so not sure if there are better options here?

I would like to know how can I update a string value in an Array node in the JSON file.

Following is a sample JSON. Please note this is not the entire file content, it's a simplified version.

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

Following is the code to read JSON into java object.

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

To update a root level node value e.g. environment in the JSON file , I found following approach on some SO threads.

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

QUESTION 1: Is this the only way to update a value in JSON file and is it the best way possible? I'm concerned on double casting and file I/O here.

QUESTION 2: I could not find a way to update the value for a nested Array node e.g. questionList. Update the question from when is the next world cup to when is the next soccer world cup

Upvotes: 0

Views: 2758

Answers (1)

Pranay Kumbhalkar
Pranay Kumbhalkar

Reputation: 701

You can use ObjectMapper to parse that JSON, it is very easy to parse and update JSON using pojo class.

use link to convert your json to java class, just paste your json here n download class structure.

You can access or update nested json field by using . (dot) operator

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

Upvotes: 5

Related Questions