如何用另一个替换Java Jackson TextNode(更新)? [英] How can I replace a Java Jackson TextNode by another one (update)?

查看:486
本文介绍了如何用另一个替换Java Jackson TextNode(更新)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标是更新JsonNode中的一些文本字段.

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?

推荐答案

简短的答案是:不能. TextNode没有公开允许您更改内容的任何操作.

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

输出为:

{"fieldName":新值",嵌套":{"fieldName":新值"}}

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

这篇关于如何用另一个替换Java Jackson TextNode(更新)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆