You had just a small problem with your code. When you add the new text entry, you have to provide the key value that you want to associate the new text node with. So this line:
nodeObj.set(newNode);
Just needs to be this:
nodeObj.set("B", newNode);
Here's a complete example that does just what you show in your question, incorporating the code you provided, with just this one small fix:
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);
}
And the resulting output:
[{"A":{"B":{"C":"Message","D":"FN1"}}}]
[{"A":{"B":"My String Message"}}]
UPDATE: Per the discussion in the comments, to make the change you illustrate, you have to have access to the ObjectNode associated with the key A. It is this ObjectNode that associates B with the ObjectNode containing C and D. Since you want to change the value that B is associated with (you want it to be associated with a TextNode instead of an ObjectNode), you need access to the ObjectNode associated with A. If you only have a pointer to the ObjectNode containing C and D, you can't make the change you want to make.