Is there a way to put a value to Jackson JsonNode like you get it with jsonNode.at("/deep/path/to/var")?

huangapple go评论61阅读模式
英文:

Is there a way to put a value to Jackson JsonNode like you get it with jsonNode.at("/deep/path/to/var")?

问题

有类似以下的东西吗?

jsonNode.put("/deep/path/to/var", "myval")

或者使用ObjectNode类似的东西?

我知道有方法可以迭代jsonNode并将内容放入其中,但我的问题是,我如何将"/deep/path/to/..."用作字符串来修改JSON中的值,或者在映射或类似的东西中修改值?

例如,我现在有以下内容:

{
  "deep": {
    "path": {
      "to": "value"
    }
  }
}

现在我想将其更改为:

{
  "deep": {
    "path": {
      "to": "otherValue"
    }
  }
}

我希望只需编写一个路径到键并更改值,而无需遍历整个树。

我不想要做的是:

myMap.get("deep").get("path").put("to", "otherValue");

我喜欢的是类似这样的东西:

mySuperfancyObject.put("deep/path/to", "otherValue");

这种可能吗?

英文:

Is there something like

jsonNode.put("/deep/path/to/var", "myval")

or something with ObjectNode?

I know there are ways to iterate over the jsonNode and put something inside but my Question is. How could I use "/deep/path/to/..." as String to modify a value in a JSOn or also inside a map or something similar?

For example what I have is

{"deep":{
 "path": {
  "to":"value" 
  }
}

And now I want to change it to

{"deep":{
 "path": {
  "to":"otherValue" 
  }
}

My wish is that I just write a path to the key and change the value without iterating through the tree.

What I don't like to do is:

myMap.get("deep").get("path").put("to","otherValue");

What I like is something fancy like:

mySuperfancyObject.put("deep/path/to", "otherValue");

Is this possible?

答案1

得分: 0

啊,好的,现在我明白如何使用

    jsonNode.at("/deep/path");

这个函数会返回一个 JsonNode,你可以在将其转换为 ObjectNode 时对其进行操作。如果你这样做,整个树都会得到更新。

所以我的代码看起来像:

JsonNode jsonNode = new ObjectMapper().valueToTree(myMap);
JsonNode nodeToSetValue = jsonNode.at("/deep/path");
String oldValue = ((ObjectNode) nodeToSetValue).get("finalKey").asText();
String newValue = changeValue(oldValue);
((ObjectNode) nodeToSetValue).put("finalKey", newValue);
myMap = new ObjectMapper().convertValue(jsonNode, new TypeReference<Map<String, Object>>(){});


<details>
<summary>英文:</summary>

Ah ok now I understand how to do it with

    jsonNode.at(&quot;/deep/path&quot;);

This function returns a JsonNode and you could manipulate it when you cast it to an ObjectNode. If you do that the whole tree get this update.

So my code looks like:

JsonNode jsonNode = new ObjectMapper().valueToTree(myMap);
JsonNode nodeToSetValue = jsonNode.at("/deep/path");
String oldValue = ((ObjectNode) nodeToSetValue).get("finalKey").asText();
String newValue = changeValue(oldValue);
((ObjectNode) nodeToSetValue).put("finalKey", newValue);
myMap = new ObjectMapper().convertValue(jsonNode, new TypeReference<Map<String, Object>>(){}));

huangapple
  • 本文由 发表于 2023年6月16日 15:37:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76487938.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定