简体   繁体   中英

Java Replace JsonNode with String value

I am a noob in Java and am struggling to with type conversions. I have a JSON Object like below:

   [  
       {  
        "A":{  
           "B":{  
              "C":"Message",
              "D":"FN1"
           }
        }
       }
    ] 

And I want to convert it like:

  [  
       {  
        "A":{  
           "B": "My String Message"
        }
       }
    ]

I am able to replace the old JSON node with new JSON node but unable to replace it with TextNode, tried multiple failed options like below:

   JsonNode newNode = new TextNode("My String Message");
   ObjectNode nodeObj = (ObjectNode) jsonNode;
   nodeObj.removeAll();
   nodeObj.set(newNode);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM