Convert JSON String to Java Object Using Jackson API

JSON stands for JavaScript Object Notation. Now a days JSON is widely used in REST APIs. When getting JSON in request we might need to convert it to Java object to proceed further. Say we are calling third party API in our Java code and that is returning below JSON and we want to convert that JSON to Java Object.
Sample JSON -
{"empId":1,"name":"John","cmpName":"Google"}

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>

Below is Employee class to which we want to get data from JSON String. Just make sure that you have default no-args constructor.

public class Employee {

 private long empId;

 private String name;

 private String cmpName;

 public Employee() {
  
 }
 
 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 convert JSON String Java Object. One thing we need to do when we provide JSON in String we need to use backward slash.
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonToJava {

 public static void main(String[] args) {
  String jsonStr = "{\"empId\":1,\"name\":\"John\",\"cmpName\":\"Google\"}";
  
  ObjectMapper objectMapper = new ObjectMapper();
  
  try {
   Employee employee = objectMapper.readValue(jsonStr, Employee.class);
   
   System.out.println("Id = " + employee.getEmpId() + " & Name = " + 
     employee.getName() + " & Company = " + employee.getCmpName());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }

}

Lets checkout out put of this.
Id = 1 & Name = John & Company = Google


Checkout Below Useful Courses :-



0 Comments