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

这一生的挚爱 提交于 2019-11-30 16:45:56

问题


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?


回答1:


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




回答2:


Because you cannot modify a TextNode, you can instead get all the parentNodes of that field, and call the put operation on it with the same field name and a new value. It will replace the existing field and change the value.

List<JsonNode> parentNodes = jsonNode.findParents("fieldName");
if(parentNodes != null) {
  for(JsonNode parentNode : parentNodes){
    ((ObjectNode)parentNode).put("fieldName", "newValue");
  }
}


来源:https://stackoverflow.com/questions/28607255/how-can-i-replace-a-java-jackson-textnode-by-another-one-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!