Thursday, 28 January 2016

Java POJO to Json with ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)

Java POJO to Json using com.fasterxml.jackson.databind.ObjectMapper
In many daily development scenarios we come across  situations where we need to convert a JAVA POJO into JSON.

There are many ways that we can use to do so. The following article shows hoe to convert a POJO class into JSON using the Jackson ObjectMapper API.

Step 1:

Download the jackson-databind-2.7.0.jar , jackson-annotations-2.7.0.jar and jackson-core-2.7.0.jar file form the link below and place it in your build path.

If you are using Maven then jackson-annotations-2.7.0.jar and jackson-core-2.7.0.jar will be downloaded automatically using the below dependency.

Step 2:

We will start by creating a simple Employee POJO class.


package net.codermag.json.examples;

public class Employee {

 private String name;
 private String email;
 private EmployeeAddress address;

 public String getName() {
  return name;

 public void setName(String name) { = name;

 public String getEmail() {
  return email;

 public void setEmail(String email) { = email;

 public EmployeeAddress getAddress() {
  return address;

 public void setAddress(EmployeeAddress address) {
  this.address = address;



package net.codermag.json.examples;

public class EmployeeAddress {

 private String city;
 private String state;

 public String getCity() {
  return city;

 public void setCity(String city) { = city;

 public String getState() {
  return state;

 public void setState(String state) {
  this.state = state;

Now that we have the structure of the POJO ready we can now convert the Employee POJO into JSON by running the following code sample.


package net.codermag.json.examples;


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

public class PojoToJsonExample {

 public static void main(String[] args) {

  // Setting values of the Employee POJO
  Employee emp1 = new Employee();

  EmployeeAddress address = new EmployeeAddress();
  address.setCity("New York");

  try {
   ObjectMapper mapper = new ObjectMapper();
   //Convert Object to plain Java String
   String json = mapper.writeValueAsString(emp1);
   //Convert Object to a pretty printed Java String
   String prettyPrintedJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp1);
   //Write to a File
   mapper.writeValue(new File("D:\\Employee.json"), emp1);
  } catch (JsonProcessingException e) {
  } catch (IOException e) {



{"name":"John","email":"","address":{"city":"New York","state":"USA"}}

No comments:

Post a Comment

Coder Magnet
CoderMagnet is full of resources from our daily development activities. It has solutions for common problematic scenarios in technologies like Java 8, AEM, JCR and also occasionally gives you tips on Blogger as well.