Apr 28, 2018

How to Convert JSON String to Java Object and Java Object to JSON String : Use Jackson API to convert JSON to Java Object

In previous post we saw how to convert JSON String to JSON Object(JsonNode) and retrieve information from it. In this post we will convert JSON string to Java class and it is very common use case when we are working with JSON in java application. Using Jackson API(a high-performance JSON processor for Java) we can convert JSON string to Java Object and vice versa

JSON String to Java Object : Using jackson ObjectMapper class we create mapper Object and readValue() method convert Sting to Java Object(specified in readValue method).
/*Creating Jackson Object Mapper*/
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
/* Converting JSON String to Employee Object */
Employee employee = objectMapper.readValue(jsonString, Employee.class);

Java Object to JSON String : Using jackson ObjectMapper class we create mapper Object and writeValueAsString() method convert Java Object to String.
ObjectMapper objectMapper = new ObjectMapper();
/* To suppress serializing properties with null value */
objectMapper.setSerializationInclusion(Include.NON_NULL);
/* To pretty print JSON String */
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
String employeeJSON = objectMapper.writeValueAsString(employeeObject);

Sample Program : Below method convertJsonStringToJavaObject() convert JSON response into Employee Object and method convertJavaObjectToJSONString() convert Employee object to JSON String.

package com.devinline.jackson;

import java.io.IOException;
import java.util.Scanner;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
/**
 * 
 * @author nikhil(www.devinline.com)
 * 
 */
public class JSONStringToJavaObject {
 public static final String jsonInput  = "{\n" + 
   "            \"employeeId\": \"ORA098\",\n" + 
   "            \"department\": \"PSR-CP\",\n" + 
   "            \"personalDetail\":{\n" + 
   "                \"firstName\": \"Nikhil\",\n" + 
   "                \"lastName\": \"Ranjan\",\n" + 
   "                \"address\": {\n" + 
   "                    \"addressLineOne\": \"House# 206\",\n" + 
   "                    \"addressLineTwo\": \"SLS APRTMENT\",\n" + 
   "                    \"zip\": 560043,\n" + 
   "                    \"state\": \"Karnataka\",\n" + 
   "                    \"country\": \"INDIA\",\n" + 
   "                    \"landmark\": \"HSR Layout\"\n" + 
   "                },\n" + 
   "                \"bloodGroup\": \"O+\"\n" + 
   "            },\n" + 
   "            \"designation\": \"Senior Engineer\"\n" + "        }";

 public static void main(String[] args) {
  System.out.println("\n1. JSON String to Java Object : ");
  System.out.println("\n2. JAVA Object to JSON String : ");
  System.out.println("\nEnter your choice: ");
  Scanner sc = new Scanner(System.in);
  int choice = sc.nextInt();
  
  switch (choice) {
  case 1:
   convertJsonStringToJavaObject();
   break;
  case 2:
   convertJavaObjectToJSONString();
  default:
   break;
  }
  sc.close();
 }

 private static void convertJsonStringToJavaObject() {
  ObjectMapper objectMapper = new ObjectMapper();
  /*
   * DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES added to deal with JSONs
   * with unknown properties
   */
  objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  try {
   /* Converting JSON String to Employee Object */
   Employee employee = objectMapper.readValue(jsonInput, Employee.class);
   System.out.println("***** Accessing Employee Object *****");
   System.out.println("Blood group of " + employee.getPersonalDetail().getFirstName() + " is "
     + employee.getPersonalDetail().getBloodGroup());
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

 private static void convertJavaObjectToJSONString() {
  ObjectMapper objectMapper = new ObjectMapper();
  /*
   * To suppress serializing properties with null values
   */
  objectMapper.setSerializationInclusion(Include.NON_NULL);
  /* To pretty print JSON String */
  objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
  Employee employee = getEmployeeObjet();
  try {
   String employeeJSON = objectMapper.writeValueAsString(employee);
   System.out.println("***** Employee JSON String is ******** \n " + employeeJSON);
  } catch (JsonProcessingException e) {
   e.printStackTrace();
  }

 }

 private static Employee getEmployeeObjet() {
  Employee employee = new Employee();
  employee.setDepartment("PSR-CP");
  employee.setEmployeeId("ORA098");
  employee.setDesignation("Senior Engineer");
  PersonalDetail pdtail = new PersonalDetail();
  pdtail.setBloodGroup("O+ve");
  pdtail.setFirstName("Nikhil");
  pdtail.setLastName("Ranjan");
  Address address = new Address();
  address.setAddressLineOne("House# 206");
  address.setAddressLineTwo("SLS APRTMENT");
  address.setCity("Bangalore");
  address.setCountry("India");
  address.setLandmark("HSR LAYOUT");
  address.setZip("560043");
  pdtail.setAddress(address);
  employee.setPersonalDetail(pdtail);
  return employee;
 }

}

Sample output:

1. JSON String to Java Object :
2. JAVA Object to JSON String :

Enter your choice:
2

***** Employee JSON String is ********
 {
  "employeeId" : "ORA098",
  "department" : "PSR-CP",
  "personalDetail" : {
    "firstName" : "Nikhil",
    "lastName" : "Ranjan",
    "bloodGroup" : "O+ve",
    "address" : {
      "addressLineOne" : "House# 206",
      "addressLineTwo" : "SLS APRTMENT",
      "landmark" : "HSR LAYOUT",
      "city" : "Bangalore",
      "zip" : "560043",
      "country" : "India"
    }
  },
  "designation" : "Senior Engineer"
}
-------------
1. JSON String to Java Object : 
2. JAVA Object to JSON String : 

Enter your choice: 
1
***** Accessing Employee Object *****
Blood group of Nikhil is O+



Reference: 


Location: Bengaluru, Karnataka, India