HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Jackson / Jackson convert object to json and json to object

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Feedback, Discussion and Comments

  1. dhanaraj

    July 30, 2019

    “{“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

    • Lokesh Gupta

      July 31, 2019

      Try this solution.

  2. Shikha Singh

    June 20, 2019

    Getter setters are missing in Employee.java due to while mapper.readValue() won’t work

    • Lokesh Gupta

      June 20, 2019

      They are removed for brevity. I have added comment in code “//Getters and setters” for this reason only.

  3. Bala

    November 23, 2017

    While passing autowired object for json parsing,

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

  4. kichu

    August 25, 2017

    (“$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?.

  5. Jon

    December 15, 2016

    Hello, please:

    How may I accomplish the same with BOTH a Model bean and a managed bean that connects the MODEL to a remote MySQL data source?

    https://stackoverflow.com/questions/41142802/jsf-managed-bean-accessing-mysql-remote-database-how-to-create-json-array-to-f

    Any suggestions greatly appreciated.

    Jon

    • Lokesh Gupta

      December 21, 2016

      Link seems dead.

  6. Rajesh

    April 13, 2016

    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”:””
    }
    }
    }
    }

    • Lokesh Gupta

      April 13, 2016

      It’s already json, dear.

      • Rajesh

        April 14, 2016

        conveting to java object Lokesh

  7. Mickael

    March 27, 2016

    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

    • Lokesh Gupta

      March 27, 2016

      Use HTTP header “Content-type” in request and set it’s value to “application/json”.

  8. alok singh

    January 7, 2016

    how to convert csv file to json file in java dynamically(csv file upload and then convert in json file using java)

  9. Manish

    June 20, 2015

    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…!!!

    • Lokesh Gupta

      June 20, 2015

      I will say, it’s known behavior. When there is only one object in list, jackson creates only an object; ignoring the fact that it is inside list. In other words, You’re trying to parse a JSON OBJECT “{ … }” as a JSON ARRAY “[ … ]”. To solve this issue, use ObjectMapper.configure( DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true );

      • Manish

        June 21, 2015

        Thanks Lokesh,

        Issue has been Resolved.

  10. Vikas

    May 2, 2015

    How we can convert below to Java object:

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

    • Manish

      June 19, 2015

      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.

  11. Ragunath

    April 29, 2015

    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?

    • Lokesh Gupta

      April 29, 2015

      It has link for downloading jar file also.

      https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl/1.9.13

  12. test

    March 23, 2015

    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

  13. Refat

    February 2, 2015

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

    • Lokesh Gupta

      February 2, 2015

      There can be only one root element. So you will have to create composite object having association of all different objects you want to read/write.

  14. Vijay

    November 14, 2014

    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.

    • Lokesh Gupta

      November 14, 2014

      See this example to understand how we can send it to the response of a web API.

  15. nitin

    October 10, 2014

    please make the source code availiable

  16. Kamlesh Kumar

    June 17, 2014

    for date its not getting serialised properly.

    • HIMANSU NAYAK

      June 18, 2014

      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;
      }

  17. sakura

    June 17, 2014

    That such the great article.
    Anyway, if I want to write more one object at once is it possible to do that? And how?

  18. HIMANSU NAYAK

    June 17, 2014

    Hi Pankaj,

    defaultPrettyPrintingWriter() is deprecated api, i am using writerWithDefaultPrettyPrinter() instead.

    • Lokesh Gupta

      June 17, 2014

      Oops !! I missed it. Updated the post.

      • devaki

        October 21, 2014

        how to run the code? Is it a normal java run or maven build?

        • Lokesh Gupta

          October 21, 2014

          JavaToJSONExample.java has main() method.

Comments are closed on this article!

Search Tutorials

JAXB Tutorial

  • JAXB – Annotations
  • JAXB – @XmlRootElement
  • JAXB – @XmlElementWrapper
  • JAXB – Marshaller
  • JAXB – Unmarshaller
  • JAXB – Convert XML to Java Object
  • JAXB – Convert JSON to Java Object
  • JAXB – Convert Java Object to XML
  • JAXB – Convert Java Object to JSON
  • JAXB – Map
  • JAXB – List and Set
  • JAXB – Generate Schema
  • JAXB – Schema Validation
  • JAXB – JAXBException
  • JAXB – IllegalAnnotationExceptions
  • JAXB – Marshal without @XmlRootElement
  • JAXB – Unmarshal without @XmlRootElement
  • Jackson 2 – Object from/to JSON
  • Jackson – Object from/to json
  • Jackson – JSON from/to Map

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces