如何将Java Jackson TextNode替换为另一个(更新)?
我的目标是更新JsonNode中的一些文本字段。
    List<JsonNode> list = json.findValues("fieldName");    for(JsonNode n : list){
        // n is a TextNode. I'd like to change its value.
    }
我不知道该怎么做。你有什么建议吗?
回答:
简短的答案是:您不能。TextNode不公开允许您更改内容的任何操作。
话虽如此,您可以轻松地在循环中或通过递归遍历节点以获得所需的行为。想象以下情况:
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”:“新值”}}
以上是 如何将Java Jackson TextNode替换为另一个(更新)? 的全部内容, 来源链接: utcz.com/qa/403329.html








