Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create JSON object using Jackson in Java [duplicate]

Tags:

java

json

jackson

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"
    }
}
like image 897
Shashank Shekher Avatar asked Dec 05 '16 05:12

Shashank Shekher


People also ask

How does Jackson convert object to JSON?

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.

Does Jackson use Java serialization?

Note that Jackson does not use java.


1 Answers

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);
like image 59
Sachin Gupta Avatar answered Oct 10 '22 08:10

Sachin Gupta