Wednesday, May 1, 2019

Convert Java Object to Json String

Q- How to convert java object to json?
We can use Jackson data-binding, which is a commonly used when dealing with JSON using Jackson API.

ObjectMapper is the main api used for data-binding. It has several methods to preform reader/writer conversion from/to Java and JSON
Typical usages are as follows:

//Read JSON and convert to java objects
ObjectMapper mapper = new ObjectMapper();
Object value = mapper.readValue(JasonSource , JavaObjectType);
//JsonSource can be File/InputStream/String/etc.

//Write JSON from java objects
ObjectMapper mapper = new ObjectMapper();
Object value = mapper.writeValue(PathOfJsonSource, JavaObjectType);
//PathOfJsonSource can be File/InputStream/String/etc.

Step 1: add JACKSON dependency into pom.xml
<dependencies>
 <dependency>
  <groupid>com.fasterxml.jackson.core</groupid>
  <artifactid>jackson-databind</artifactid>
  <version>2.5.3</version>
 </dependency>
</dependencies>
Step 2: Create POJO
These object need to be converted to and from JSON.

package com.shubh.example.JsonJacksonObjectMappingExample;
public class Employee {

 long id;
 String name;
 String address;
 String email;

 public long getId() {
  return id;
 }

 public void setId(long id) {
  this.id = id;
 }

 public String getName() {
  return name;
 }

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

 public String getAddress() {
  return address;
 }

 public void setAddress(String address) {
  this.address = address;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 @Override
 public String toString() {
  return "Id:" + id + ", Name :" + name + ", Email: " + email + ", Address: " + address;
 }
}
Step 3: Convert Java Object to JSON and write JSON to a file

package com.shubh.example.JsonJacksonObjectMappingExample;
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MainClassWriteJson {

 public static void main(String[] args) {

  Employee employee = new Employee();
  employee.setId(1);
  employee.setName("Deepak Kumar");
  employee.setEmail("deepak@xyz.com");
  employee.setAddress("New Delhi");

  ObjectMapper mapper = new ObjectMapper();
  /* Write object to file */
  try {
   /* Plain JSON */
   mapper.writeValue(new File("result.json"), employee);
   /* To Print Pretty JSON */
   // mapper.writerWithDefaultPrettyPrinter().writeValue(new
   // File("result.json"), employee);


   /*OR we can get Json Sting*/
   /*get Employee object to json string */
   String employeeJson = mapper.writeValueAsString(employee); 
   /*Print JSON String*/ 
   System.out.println(employeeJson); 
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Output:

{"id":1,"name":"Deepak Kumar","address":"New Delhi","email":"deepak@xyz.com"}
Step 4: Read JSON from a file and convert into Java Object

package com.shubh.example.JsonJacksonObjectMappingExample;
import java.io.File;
import com.fasterxml.jackson.databind.ObjectMapper;

public class MainClassReadJson {

 public static void main(String[] args) {
  ObjectMapper mapper = new ObjectMapper();
  /* Write object to file */
  Employee empObject = null;
  try {
   empObject = mapper.readValue(new File("result.json"), Employee.class);
   System.out.println(empObject);
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}
Output:

Id:1, Name :Deepak Kumar, Email: deepak@xyz.com, Address: New Delhi

No comments:

Post a Comment