Home > database >  Not able to update the values in jscon file -jackson
Not able to update the values in jscon file -jackson

Time:10-12

I am trying to update this json file:

{
  "name": "abc",
  "age": "123",
  "project-name": "Test",
  "city": "pune",
  "project-git": "Test",
  "notification": {
    "email-subject": "Test"
  }
}

I am trying to change project-name and email-subject to some other value.

The code to change email-subject is as follows:

ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File("abc.json");

JsonNode root = objectMapper.readTree(jsonFile);
JsonNode steps = root.get("notification");


for (final JsonNode item: steps) {
    if (item.findPath("email-subject") != null) {
        ((ObjectNode) item).put("email-subject", "Test update");
    }
}

String resultJson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);

And the code to update project-name is as follows:

ObjectMapper objectMapper = new ObjectMapper();
File jsonFile = new File("bac.json");

JsonNode root = objectMapper.readTree(jsonFile);

((ObjectNode) item).put("project-name", "update name")
objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(root);

In both cases, I am getting this exception:

Error : Exception in thread "main" java.lang.ClassCastException: com.fasterxml.jackson.databind.node.TextNode cannot be cast to com.fasterxml.jackson.databind.node.ObjectNode

Any help would be appreciated

CodePudding user response:

notification is an objectNode. You can access its fields directly.

JsonNode root = objectMapper.readTree(jsonFile);
JsonNode steps = root.get("notification");

((ObjectNode) root).put("project-name", "update name");
if (((ObjectNode) steps).has("email-subject")) {
    ((ObjectNode) steps).put("email-subject", "Test update");
}
  • Related