如何用另一个(更新)替换 Java Jackson TextNode?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28607255/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I replace a Java Hymanson TextNode by another one (update)?
提问by yo_haha
My goal is to update some textual fields in a JsonNode.
我的目标是更新 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?
我不明白这是怎么做到的。你有什么建议吗?
采纳答案by wassgren
The short answer is: you can't. TextNode
does not expose any operations that allows you to alter the contents.
简短的回答是:你不能。TextNode
不公开任何允许您更改内容的操作。
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"}}
{"fieldName":"new value","nested":{"fieldName":"new value"}}
回答by Harshad Vyawahare
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.
因为您无法修改 TextNode,所以您可以获取该字段的所有 parentNode,并使用相同的字段名称和新值对其调用 put 操作。它将替换现有字段并更改值。
List<JsonNode> parentNodes = jsonNode.findParents("fieldName");
if(parentNodes != null) {
for(JsonNode parentNode : parentNodes){
((ObjectNode)parentNode).put("fieldName", "newValue");
}
}