I need to create a JSON string as below using Jackson. I know similar question has been answered already here: 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"
}
}
Converting Java object to JSON In it, create an object of the POJO class, set required values to it using the setter methods. Instantiate the ObjectMapper class. Invoke the writeValueAsString() method by passing the above created POJO object. Retrieve and print the obtained JSON.
Note that Jackson does not use 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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With