Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I replace a Java Jackson TextNode by another one (update)?

My goal is to update some textual fields in a JsonNode.

    List<JsonNode> list = json.findValues("fieldName");
    for(JsonNode n : list){
        // n is a TextNode. I'd like to change its value.
    }

I don't see how this could be done. Do you have any suggestion?

like image 294
yo_haha Avatar asked Feb 19 '15 13:02

yo_haha


People also ask

How do I modify JsonNode?

The JsonNode class is immutable. That means we cannot modify it.

What is Jackson used for in Java?

Jackson is one such Java Json library used for parsing and generating Json files. It has built in Object Mapper class which parses json files and deserializes it to custom java objects. It helps in generating json from java objects.

What is JsonNode Jackson?

JsonNode is Jackson's tree model (object graph model) for JSON. Jackson can read JSON into a JsonNode instance, and write a JsonNode out to JSON. This Jackson JsonNode tutorial will explain how to deserialize JSON into a JsonNode and serialize a JsonNode to JSON.

What is ObjectNode in Java?

A ObjectNode provides a node for a linked list with Object data in each node.


1 Answers

The short answer is: you can't. TextNode does not expose any operations that allows you to alter the contents.

With that being said, you can easily traverse the nodes in a loop or via recursion to get the desired behaviour. Imagine the following:

public class JsonTest {
    public static void change(JsonNode parent, String fieldName, String newValue) {
        if (parent.has(fieldName)) {
            ((ObjectNode) parent).put(fieldName, newValue);
        }

        // Now, recursively invoke this method on all properties
        for (JsonNode child : parent) {
            change(child, fieldName, newValue);
        }
    }

    @Test
    public static void main(String[] args) throws IOException {
        String json = "{ \"fieldName\": \"Some value\", \"nested\" : { \"fieldName\" : \"Some other value\" } }";
        ObjectMapper mapper = new ObjectMapper();
        final JsonNode tree = mapper.readTree(json);
        change(tree, "fieldName", "new value");
        System.out.println(tree);
    }
}

The output is:

{"fieldName":"new value","nested":{"fieldName":"new value"}}

like image 79
wassgren Avatar answered Sep 19 '22 11:09

wassgren