Convert Java Object To JSON String Using Jackson API

JSON stands for JavaScript Object Notation. Now a days JSON is widely used in REST APIs. Many times we are in need to convert Java Object into JSON. So in this article we will see how to convert Java Object into JSON using Jackson API.

First thing add below Jackson dependency in your pom.xml.


<dependency>
 <groupId>com.fasterxml.jackson.core</groupId>
 <artifactId>jackson-databind</artifactId>
 <version>2.9.9</version>
</dependency>

Now let's have Employee class which we want to convert to JSON. So below is our Employee class. Its POJO (Plain Old Java Object) which has some fields, getters and setters and one constructor with all fields.


public class Employee {

 private long empId;

 private String name;

 private String cmpName;

 public Employee(long empId, String name, String cmpName) {
  this.empId = empId;
  this.name = name;
  this.cmpName = cmpName;
 }

 public long getEmpId() {
  return empId;
 }

 public void setEmpId(long empId) {
  this.empId = empId;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public String getCmpName() {
  return cmpName;
 }

 public void setCmpName(String cmpName) {
  this.cmpName = cmpName;
 }

}

Now lets have our main class where we will create one Object of Employee class and using Jackson we will convert it to JSON String.


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JavaToJson {

 public static void main(String[] args) {
  Employee employee = new Employee(1L, "John", "Google");

  ObjectMapper objectMapper = new ObjectMapper();

  String jsonString;

  try {

   jsonString = objectMapper.writeValueAsString(employee);

   System.out.println(jsonString);

  } catch (JsonProcessingException e) {
   e.printStackTrace();
  }
 }

}

Lets see output of this that we can see in console.


{"empId":1,"name":"John","cmpName":"Google"}


Checkout Below Useful Courses :-



0 Comments