How to add an ObjectNode into another ObjectNode as a child using Jackson?

霸气de小男生 提交于 2019-12-13 17:18:06

问题


I have the below ObjectNode.

handlerObjectNode -> {"Info":{"Brand":{"BrandName":"TOP OF THE WORLD"}}}

I have another ObjectNode in the following format.

fieldObjects -> {"Description":"REGULAR BR"}

How can I create the below ObjectNode from the above two?

{
   "Info": {
       "Brand": {
           "BrandName": "TOP OF THE WORLD"
       }
   "Description": "REGULAR BR"
   }
 }

I tried the below code.

handlerObjectNode.setAll(fieldObjects);

But it results in the following ObjectNode.

{
   "Info": {
       "Brand": {
           "BrandName": "TOP OF THE WORLD"
       }
   },
   "Description": "REGULAR BR"
 }

I am using the com.fasterxml.jackson.databind.node.ObjectNode from Jackson. Any help would be much appreciated.


回答1:


Try This,

  root.with("Info").put("Description", "REGULAR BR");

For more info This




回答2:


Extract the Info object and add the fieldObjects to that:

ObjectMapper om = new ObjectMapper();

ObjectNode handlerObjectNode = (ObjectNode) om.readTree("{\"Info\":{\"Brand\":{\"BrandName\":\"TOP OF THE WORLD\"}}}");
ObjectNode fieldObjects = (ObjectNode) om.readTree("{\"Description\":\"REGULAR BR\"}");

ObjectNode info = (ObjectNode) handlerObjectNode.path("Info");
info.setAll(fieldObjects);

Results in the following output:

{
  "Info" : {
    "Brand" : {
      "BrandName" : "TOP OF THE WORLD"
    },
    "Description" : "REGULAR BR"
  }
}


来源:https://stackoverflow.com/questions/41712865/how-to-add-an-objectnode-into-another-objectnode-as-a-child-using-jackson

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!