jsonnode修改值java,在Java中动态修改未知JSON的JsonNode

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.JsonPath library for the same.

The problem with JsonPath is, it returns me the value but I am not able to modify the Target Node.

Follows is my code snippet for the same

JsonPath.read(jsonFile, jsonPath);

JsonPath.parse(jsonPath);

System.out.println("Author: "+JsonPath.read(jsonFile, jsonPath));

I tried using Jackson as mentioned in previously asked quetion, But it needs to be traversed node by node as follows

((ObjectNode) parent).put(fieldName, newValue);

which I cannot do due to unknown structure.

I have tried the answer given to the question recursively parse JSON object but it says how to parse not modify

I need to do the follows

JsonNode root = mapper.readTree("Json in form of String");

((JsonNode)(root.get("JsonPath")).set("New Value");

Is there any way in which this can be achieved?

解决方案

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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值