你的代码有点小问题。添加新文本条目时,必须提供要与新文本节点关联的键值。所以这一行:
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"}}]