Modify JsonNode of unknown JSON dynamically in Java

后端 未结 1 984
我在风中等你
我在风中等你 2020-12-21 04:47

I am trying to modify a JSON (of an unknown structure) where the JsonPath and its equivalent XML Xpath is known to me.

I have tired using com.jayway.jsonpath.J

相关标签:
1条回答
  • 2020-12-21 05:27

    JsonNode objects are immutable so you can't modify them. What you can do is replace a JsonNode with another one. A cast to ObjectNode is also required to expose the required methods. First find the parent of the node you want to replace :

    JsonNode node = root.findParent("JsonPath");
    

    Then use either of these 2 methods to replace it with a new one:

    ((ObjectNode) node).remove("JsonPath");           // remove current node
    ((ObjectNode) node).put("JsonPath", "New Value"); // add new one with new value
    

    or

    ((ObjectNode) node).replace("JsonPath", new TextNode("New Value"));
    
    0 讨论(0)
提交回复
热议问题