How to convert Java object to JSON using Jackson library?


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

<dependency>
   <groupId>com.fasterxml.jackson.core</groupId>
   <artifactId>jackson-databind</artifactId>
   <version>2.10.0.pr2</version>
</dependency>
  • 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.

Example

import com.google.gson.Gson;
class Student {
   private int id;
   private String name;
   private int age;
   private long phone;
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.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) {
      this.phone = phone;
   }
}
public class JacksionExample {
   public static void main(String args[]) throws Exception {
      Student std = new Student();
      std.setId(001);
      std.setName("Krishna");
      std.setAge(30);
      std.setPhone(9848022338L);
      //Creating the ObjectMapper object
      ObjectMapper mapper = new ObjectMapper();
      //Converting the Object to JSONString
      String jsonString = mapper.writeValueAsString(std);
      System.out.println(jsonString);
   }
}

Output

{"id":1,"name":"Krishna","age":30,"phone":9848022338}
raja
Published on 10-Oct-2019 10:07:05
Advertisements