sammy333
sammy333

Reputation: 1445

How do I insert a Json node into another one in Java?

I have one Json node:

{
    "name":
    {
        "first": "Tatu",
        "last": "Saloranta"
    },
    "title": "Jackson founder",
    "company": "FasterXML"
}

I have another Json node (the one which I want to insert):

{
    "country": "My country",
    "hobbies": "some hobbies"
}

I want my resulting node to be:

{
    "additional info":
    {
        "country": "My country",
        "hobbies": "some hobbies"
    },
    "name": 
    {
        "first": "Tatu",
        "last": "Saloranta"
    },
    "title": "Jackson founder",
    "company": "FasterXML"
}

How do I do that in Java? Here is my java code:

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)

Upvotes: 1

Views: 2850

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44962

Instead of JsonNode read a Map and use standard Map.put() to modify the bigger object:

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

will output:

{
  "name" : {
    "first" : "Tatu",
    "last" : "Saloranta"
  },
  "title" : "Jackson founder",
  "company" : "FasterXML",
  "additional_info" : {
    "country" : "My country",
    "hobbies" : "some hobbies"
  }
}

Upvotes: 3

Related Questions