如何在Java中将Json节点插入另一个节点?

时间:2019-01-17 11:10:45

标签: java json jackson

我有一个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)

1 个答案:

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