1

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)
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111
sammy333
  • 1,384
  • 6
  • 21
  • 39
  • Look into this : - https://stackoverflow.com/questions/20117148/how-to-create-json-object-using-string – AConsumer Jan 17 '19 at 11:31
  • 1
    JsonNode is intended to be a read-only structure. In order to mutate the structure, you need to cast it to an ObjectNode. More info here: https://stackoverflow.com/a/30997696/2472905 – Robert Dean Jan 17 '19 at 11:31

1 Answers1

3

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"
  }
}
Karol Dowbecki
  • 43,645
  • 9
  • 78
  • 111