有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用Jackson将ObjectNode作为子对象添加到另一个ObjectNode中?

我有下面的ObjectNode

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"
 }

我正在使用com。fasterxml。杰克逊。数据绑定。节点。来自Jackson的ObjectNode。任何帮助都将不胜感激


共 (3) 个答案

  1. # 1 楼答案

    试试这个

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

    有关详细信息,请单击here

  2. # 2 楼答案

    提取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"
      }
    }
    
  3. # 3 楼答案

    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}}