如何使用 Jackson 将一个 ObjectNode 作为子节点添加到另一个 ObjectNode 中?

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

我有以下对象节点。

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

我有另一个 ObjectNode,格式如下。

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

如何从以上两个创建下面的 ObjectNode?

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

我试过下面的代码。

handlerObjectNode.setAll(fieldObjects);

但它会产生以下 ObjectNode。

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

我正在使用 Jackson 的 com.fasterxml.jackson.databind.node.ObjectNode。任何帮助将不胜感激。

提取 Info 对象并向其添加 fieldObjects

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);

结果如下:

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

试试这个,

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

有关详细信息,请单击 here

ObjectMapper mapper = new ObjectMapper();

//create root node
ObjectNode rootNode =  mapper.createObjectNode();

root.put("key1", "value1");
jsonObject.put("key2", "value2");

jsonObject.putArray("array2").add("item1").add("item2").add(12); //tuple
// create child node
ObjectNode childNode = mapper.createObjectNode();
        childNode.put("name", "Hungbeo");
        childNode.put("age", 12);

// add childNode to rootNode
rootNode.set("user", childNode);

System.out.println(rootNode.toString());

输出:

{"key1":"value1","key2":"value2","array":["item1","item2",12],"user":{"name":"Hungbeo","age":12}}