Create JSON object using Jackson in Java

JavaJsonJackson

Java Problem Overview


I need to create a JSON string as below using Jackson. I know similar question has been answered already here: https://stackoverflow.com/questions/16974474/creating-a-json-object-using-jackson

But my expected JSON string is a little different from the one in above example.

How can I form the below formatted JSON object in Java using only Jackson? Also, I do not prefer creating a separate POJO to achieve this.

Expected Output:

{
    "obj1": {
    	"name1": "val1",
    	"name2": "val2"
    },
    "obj2": {
    	"name3": "val3",
    	"name4": "val4"
    },
    "obj3": {
    	"name5": "val5",
    	"name6": "val6"
    }
}

Java Solutions


Solution 1 - Java

Try this:

ObjectMapper mapper = new ObjectMapper();
ObjectNode rootNode = mapper.createObjectNode();

ObjectNode childNode1 = mapper.createObjectNode();
childNode1.put("name1", "val1");
childNode1.put("name2", "val2");

rootNode.set("obj1", childNode1);

ObjectNode childNode2 = mapper.createObjectNode();
childNode2.put("name3", "val3");
childNode2.put("name4", "val4");

rootNode.set("obj2", childNode2);

ObjectNode childNode3 = mapper.createObjectNode();
childNode3.put("name5", "val5");
childNode3.put("name6", "val6");
    
rootNode.set("obj3", childNode3);


String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(rootNode);
System.out.println(jsonString);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionShashank ShekherView Question on Stackoverflow
Solution 1 - JavaSachin GuptaView Answer on Stackoverflow