How to convert Java object to JSON using Jackson library?

JavaObject Oriented ProgrammingProgrammingJSON

JSON or JavaScript Object Notation is a lightweight text-based open standard designed for human-readable data interchange. Conventions used by JSON are known to programmers, which include C, C++, Java, Python, Perl, etc.

There are several Java libraries available to handle JSON objects. Jackson is a simple java based library to serialize java objects to JSON and vice versa.

Converting Java object to JSON

The ObjectMapper class of the Jackson API in Java provides methods to convert a Java object to JSON object and vice versa.

The writeValueAsString() method of this class accepts a JSON object as a parameter and returns its respective JSON String

Therefore, to convert a Java object to a JSON String using Jackson library −

  • Add the following maven dependency to your pom.xml

  • Create a javabean/POJO object with private variables and setter/getter methods.

  • Create another class (make sure that the POJO class is available to this).

  • 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.


class Student {
   private int id;
   private String name;
   private int age;
   private long phone;
   public int getId() {
      return id;
   public void setId(int id) { = id;
   public String getName() {
      return name;
   public void setName(String name) { = name;
   public int getAge() {
      return age;
   public void setAge(int age) {
      this.age = age;
   public long getPhone() {
      return phone;
   public void setPhone(long phone) { = phone;
public class JacksionExample {
   public static void main(String args[]) throws Exception {
      Student std = new Student();
      //Creating the ObjectMapper object
      ObjectMapper mapper = new ObjectMapper();
      //Converting the Object to JSONString
      String jsonString = mapper.writeValueAsString(std);


Published on 10-Oct-2019 10:07:05