[英]Obtain the JsonNode from a Promise[JsonNode] in Java and return that value
[英]Java Replace JsonNode with String value
我是Java的菜鸟,正在努力进行类型转换。 我有一个JSON对象,如下所示:
[
{
"A":{
"B":{
"C":"Message",
"D":"FN1"
}
}
}
]
我想将其转换为:
[
{
"A":{
"B": "My String Message"
}
}
]
我可以将旧的JSON节点替换为新的JSON节点,但无法将其替换为TextNode,尝试了以下多个失败的选项:
JsonNode newNode = new TextNode("My String Message");
ObjectNode nodeObj = (ObjectNode) jsonNode;
nodeObj.removeAll();
nodeObj.set(newNode);
您的代码只有一个小问题。 添加新文本条目时,必须提供要与新文本节点关联的键值。 所以这行:
nodeObj.set(newNode);
只是需要这样:
nodeObj.set("B", newNode);
这是一个完整的示例,它完全按照您的问题显示,并结合了您提供的代码,并提供了一个小解决方案:
public static void main(String... args) throws IOException {
// Read in the structure provided from a text file
FileReader f = new FileReader("/tmp/foox.json");
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readTree(f);
// Print the starting structure
System.out.println(rootNode);
// Get the node we want to operate on
ObjectNode jsonNode = (ObjectNode)rootNode.get(0).get("A");
// The OPs code, with just the small change of adding the key value when adding the new String
JsonNode newNode = new TextNode("My String Message");
ObjectNode nodeObj = (ObjectNode) jsonNode;
nodeObj.removeAll();
nodeObj.set("B", newNode);
// Print the resulting structure
System.out.println(rootNode);
}
以及结果输出:
[{"A":{"B":{"C":"Message","D":"FN1"}}}]
[{"A":{"B":"My String Message"}}]
更新:根据注释中的讨论,要进行更改,您必须访问与键A关联的ObjectNode。正是该ObjectNode才将B与包含C和D的ObjectNode关联。与B关联的值(您希望它与TextNode而不是与ObjectNode关联),您需要访问与A关联的ObjectNode。如果只有指向包含C和D的ObjectNode的指针,则可以进行您想要的更改。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.