How to Write Jackson JsonNode to String After Modification?

The end goal here is (in Java/Spring unit test) to essentially read a JSON text from a file, update a value of some field, then write it to a String.

What I am doing is to parse the whole file into a String:

FileUtils.readFileToString(/* file location */, StandardCharsets.UTF_8);

Then read it to a JsonNode using an ObjectMapper:

JsonNode rootNode = mapper.readTree(jsonStr);

Find the field and update the field, e.g.,:

JsonNode target = rootNode.path("parent").path("child1");
((ObjectNode) target.path("field")).put("innerField", "somevalue");

However, if I write it to String using ObjectMapper, the new value (somevalue) doesn’t get registered, e.g.,

LOG.info("New JSON: {}", mapper.writeValueAsString(rootNode));

I’m doing this in a test, so it doesn’t need to be anything robust. Just need to manipulate a field in a text json and use it for another operation. It appears that JsonNode is immutable and this can’t be done using this method.

>Solution :

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;

// Read JSON file into a JsonNode object
String jsonStr = FileUtils.readFileToString(/* file location */, 
StandardCharsets.UTF_8);
JsonNode rootNode = new ObjectMapper().readTree(jsonStr);

// Find the field and update the value
ObjectNode target = (ObjectNode) 
rootNode.path("parent").path("child1").path("field");
target.set("innerField", new ObjectMapper().valueToTree("somevalue"));

// Convert the updated JsonNode to a string
String updatedJsonStr = new ObjectMapper().writeValueAsString(rootNode);
LOG.info("New JSON: {}", updatedJsonStr);

First you read the JSON file into a JsonNode object using the ObjectMapper. Then we use the path() method to navigate to the field we want to update and cast it to an ObjectNode, which is a mutable implementation of JsonNode. We use the set() method to update the value of the innerField property.

Finally, we use the writeValueAsString() method of the ObjectMapper to convert the updated JsonNode object back to a JSON string.

Leave a Reply