[英]How to add an ObjectNode into another ObjectNode as a child using Jackson?
I have the below ObjectNode.我有以下 ObjectNode。
handlerObjectNode -> {"Info":{"Brand":{"BrandName":"TOP OF THE WORLD"}}}
I have another ObjectNode in the following format.我有以下格式的另一个 ObjectNode。
fieldObjects -> {"Description":"REGULAR BR"}
How can I create the below ObjectNode from the above two?如何从上述两个创建以下 ObjectNode?
{
"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.但它会导致以下 ObjectNode。
{
"Info": {
"Brand": {
"BrandName": "TOP OF THE WORLD"
}
},
"Description": "REGULAR BR"
}
I am using the com.fasterxml.jackson.databind.node.ObjectNode from Jackson.我正在使用 Jackson 的 com.fasterxml.jackson.databind.node.ObjectNode。 Any help would be much appreciated.任何帮助将非常感激。
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());
Output:输出:
{"key1":"value1","key2":"value2","array":["item1","item2",12],"user":{"name":"Hungbeo","age":12}}
Extract the Info
object and add the fieldObjects
to that:提取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);
Results in the following output:结果如下:
{
"Info" : {
"Brand" : {
"BrandName" : "TOP OF THE WORLD"
},
"Description" : "REGULAR BR"
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.