Jackson convert object to json and json to object

Jackson convert object to JSON example and convert json to object example. Learn to use jackson objectmapper to populate java object from json string and write json string from java object.

Jackson is used to convert java object to json, and convert json to java object. In this quick jackson tutorial, I am giving examples of converting java objects to/from json programmatically.

Table of Contents

1. Jackson maven dependency
2. Convert Java object to JSON
3. Pretty print JSON
4. Convert JSON to Java object

Before jumping into code examples, lets define a simple pojo class which we will use in this example for conversion purpose.

public class Employee
{
   private Integer id;
   private String firstName;
   private String lastName;

   public Employee(){

   }

   public Employee(Integer id, String firstName, String lastName, Date birthDate){
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
   }

   //Getters and setters

   @Override
   public String toString()
   {
      return "Employee [id=" + id + ", firstName=" + firstName + ", " +
            "lastName=" + lastName + "]";
   }
}

1. Jackson dependency

You can add Jackson dependency in two ways depending on your project type.

1.1. Maven based project

Add following dependency in your pom.xml file.

<dependencies>
	<dependency>
	    <groupId>com.fasterxml.jackson.core</groupId>
	    <artifactId>jackson-core</artifactId>
	    <version>2.9.6</version>
	</dependency>
</dependencies>

1.2. For ANT or other project types

For non-Maven use cases, you download jars from Central Maven repository.

2. Jackson ObjectMapper

ObjectMapper is the main api used for data-binding. It comes with several reader/writer methods to preform the conversion from/to Java and JSON. It will use instances of JsonParser and JsonGenerator for implementing actual reading/writing of JSON.

2.1. Syntax to convert json to object

Use below sample syntax to read JSON and populate java objects.

ObjectMapper mapper = new ObjectMapper();
Object value = mapper.readValue(jsonSource , javaObject);
  • jsonSource – The input source which will fetch the json string.
  • javaObject – The target Java object which needs to be populated.

2.2. Syntax to convert object to json

Use below sample syntax to write java object to json string.

ObjectMapper mapper = new ObjectMapper();
Object value = mapper.writeValue(jsonTarget, javaObject);
  • jsonTarget – The output target where json string will be written.
  • javaObject – The source Java object which needs to be converted to json.

3. Jackson convert object to JSON

To convert the employee object and write it to some file, to can use below code.

package test.jackson;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JavaToJSONExample
{
   public static void main(String[] args)
   {
      @SuppressWarnings("deprecation")
      Employee employee = new Employee(1, "Lokesh", "Gupta", new Date(1981,8,18));
      ObjectMapper mapper = new ObjectMapper();
      try
      {
         mapper.writeValue(new File("c://temp/employee.json"), employee);
      } catch (JsonGenerationException e)
      {
         e.printStackTrace();
      } catch (JsonMappingException e)
      {
         e.printStackTrace();
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

Program Output.

{"id":1,"firstName":"Lokesh","lastName":"Gupta"}

4. Jackson pretty print JSON output

If you look at above output, then the output written in text file is very raw and not formatted. You can write a formatted JSON content using defaultPrettyPrintingWriter() writerWithDefaultPrettyPrinter instance like below:

package test.jackson;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JavaToPrettyJSONExample
{
   public static void main(String[] args)
   {
      @SuppressWarnings("deprecation")
      Employee employee = new Employee(1, "Lokesh", "Gupta", new Date(1981,8,18));
      ObjectMapper mapper = new ObjectMapper();
      try
      {
         mapper.defaultPrettyPrintingWriter().writeValue(new File("c://temp/employee.json"), employee);
      } catch (JsonGenerationException e)
      {
         e.printStackTrace();
      } catch (JsonMappingException e)
      {
         e.printStackTrace();
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

Program Output.

{
  "id" : 1,
  "firstName" : "Lokesh",
  "lastName" : "Gupta"
}

5. Jackson convert JSON to Java object

To convert a json string to java object (e.g. Employee object) use below code:

package test.jackson;

import java.io.File;
import java.io.IOException;

import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

public class JSONToJavaExample
{
   public static void main(String[] args)
   {
      Employee employee = null;
      ObjectMapper mapper = new ObjectMapper();
      try
      {
         employee =  mapper.readValue(new File("c://temp/employee.json"), Employee.class);
      } catch (JsonGenerationException e)
      {
         e.printStackTrace();
      } catch (JsonMappingException e)
      {
         e.printStackTrace();
      } catch (IOException e)
      {
         e.printStackTrace();
      }
      System.out.println(employee);
   }
}

Program Output.

Employee [id=1, firstName=Lokesh, lastName=Gupta]
Make sure you have defined a default constructor in your POJO class (e.g. Employee.java in our case). Jackson uses default constructor to create the instances of java class using reflection. If default constructor is not provided, then you will get JsonMappingException in runtime.

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

34 thoughts on “Jackson convert object to json and json to object”

  1. “{“timestamp”:”2019-07-29T06:53:14.290+0000″,”status”:400,”error”:”Bad Request”,”message”:”
    JSON parse error: Cannot deserialize instance of `java.util.Date` out of START_OBJECT token; nested exception is
    com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `java.util.Date`
    out of START_OBJECT token\n at [Source: (PushbackInputStream);

    hai how to solve the above problem

    Reply
  2. While passing autowired object for json parsing,

    msg:com.fasterxml.jackson.databind.JsonMappingException: Direct self-reference leading to cycle (through reference chain:

    Reply
  3. (“$BEO,2.3,1105,V837152325,1,250417172030,110,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0”) i want split the comma seperated string into 3 values in each substring later i want to convert each sub string to json. how to do tat?.

    Reply
  4. Hi Lokesh, i have this json file can u plz tell how to convert to json
    {
    “ImplCreateBanRestOutput”:{
    “baseOutput”:{
    “ban”:””,
    “statusCodes”:[
    {
    “status”:true,
    “activityType”:””,
    “additionalInfo”:””,
    “errorCode”:””
    },
    {
    “status”:true,
    “activityType”:””,
    “additionalInfo”:””,
    “errorCode”:””
    }
    ],
    “responseInfo”:{
    “code”:””,
    “serverTS”:”2016-03-01T13:56:51.805+0200″,
    “messageId”:””
    }
    }
    }
    }

    Reply
  5. Hello,

    I want to send from an external app a json object POST API . How to make the API understands that the parameter is a JSON object and the interpreter ?

    thanks in advance

    Reply
  6. Hi Lokesh,
    Thanks for sharing such a nice tutorial..
    I am using jackson library to parse JSON to POJO
    Here I am in trouble while parsing….My json is dynamically changed..
    I am using REST api to get json response..
    Response example :
    “ValueAdds”: {
    “@size”: “3”,
    “ValueAdd”: [
    {
    “@id”: “128”,
    “description”: “Free Parking”
    },
    {
    “@id”: “2048”,
    “description”: “Free Wireless Internet”
    },
    {
    “@id”: “16777216”,
    “description”: “Breakfast Buffet”
    }
    ]
    }

    and sometimes….

    “ValueAdds”: {
    “@size”: “1”,
    “ValueAdd”: {
    “@id”: “16777216”,
    “description”: “Breakfast Buffet”
    }
    }

    public class ValueAdds {

    @JsonProperty(“@size”)
    private String Size;
    @JsonProperty(“ValueAdd”)
    private List ValueAdd = new ArrayList();
    //getters and setters
    }

    and my pojo expecting List of “ValueAdd”.. so getting error like “Can not deserialize instance of java.util.ArrayList out of START_OBJECT token”

    Please help me on this..
    Thanks in Advance…!!!

    Reply
  7. How we can convert below to Java object:

    {
    “options”: [
    {
    “text”: “111”,
    “label”: “ABC”
    },
    {
    “text”: “222”,
    “label”: “DEF”
    },
    {
    “text”: “333”,
    “label”: “GHI”
    }
    ]
    }

    Reply
    • Hi Vikas,

      You should create one more class as options containing text and label as String..
      and here options seems to be json array…so for that you need to create List of options in class where your jsonarray resides.. like..

      “Employee” :
      {
      “options”: [
      {………………………………………
      you have create List list; in class Employee.

      Hope this helps.

      Reply
  8. Hi Lokesh,

    I could not find the JACKSON latest jar file t execute the above sample code. I am using the ANT project type.
    Can you please share the jar file link to download?

    Reply
  9. I’m getting wired error and unable to get solution for that. Could you please help?

    org.springframework.http.converter.HttpMessageNotReadableException: Could not read JSON:
    Can not deserialize instance of java.lang.String out of START_OBJECT token

    Reply
  10. Hi, the above example reads only one object……how to make it read more than one object….may be a silly question……please help!!!

    Reply
  11. Hey Lokesh,

    Suppose I have list of java objects say List and I want to convert it to json so that I can later pass it as ajax response. How can we achieve this.

    In above example we are writing java object directly to file instead of that I want to hold it.

    Please reply.

    Reply
    • Hi Pankaj,

      Employee constructor is not using date value for initialization in employee.java.

      public Employee(Integer id, String firstName, String lastName, Date birthDate){
      this.id = id;
      this.firstName = firstName;
      this.lastName = lastName;
      }

      Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.