我有一个Json节点:
{
"name":
{
"first": "Tatu",
"last": "Saloranta"
},
"title": "Jackson founder",
"company": "FasterXML"
}
我还有另一个Json节点(我要插入的那个节点):
{
"country": "My country",
"hobbies": "some hobbies"
}
我希望得到的结点是:
{
"additional info":
{
"country": "My country",
"hobbies": "some hobbies"
},
"name":
{
"first": "Tatu",
"last": "Saloranta"
},
"title": "Jackson founder",
"company": "FasterXML"
}
如何用Java做到这一点?这是我的Java代码:
private final static ObjectMapper JSON_MAPPER = new ObjectMapper();
JsonNode biggerNode = parseTree(someObject);
JsonNode nodeToBeInsertede = JSON_MAPPER.valueToTree(anotheObj);
//I want to do something like this:
//biggerNode.put("additionalInfo", nodeToBeInsertede)
答案 0 :(得分:2)
读取JsonNode
而不是Map
并使用标准的Map.put()
来修改较大的对象:
ObjectMapper mapper = new ObjectMapper().enable(SerializationFeature.INDENT_OUTPUT);
TypeReference<Map<String, Object>> type = new TypeReference<>() {};
Map<String, Object> biggerMap = mapper.readValue(biggerJson, type);
Map<String, Object> smallerMap = mapper.readValue(smallerJson, type);
biggerMap.put("additional_info", smallerMap);
String outJson = mapper.writeValueAsString(biggerMap);
System.out.println(outJson);
将输出:
{
"name" : {
"first" : "Tatu",
"last" : "Saloranta"
},
"title" : "Jackson founder",
"company" : "FasterXML",
"additional_info" : {
"country" : "My country",
"hobbies" : "some hobbies"
}
}