How to convert Java object to / from JSON (Jackson)

Jackson is a High-performance JSON processor Java library. In this tutorial, we show you how to use Jackson’s data binding to convert Java object to / from JSON.

For object/json conversion, you need to know following two methods :

//1. Convert Java object to JSON format
ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);
//2. Convert JSON to Java object
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(new File("c:\\user.json"), User.class);
Both writeValue() and readValue() has many overloaded methods to support different type of inputs and outputs. Make sure check it out.

1. Jackson Dependency

Jackson contains 6 separate jars for different purpose, check here. In this case, you only need “jackson-mapper-asl” to handle the conversion, just declares following dependency in your pom.xml


For non-maven user, just get the Jackson library here.


An user object, initialized with some values. Later use Jackson to convert this object to / from JSON.

package com.mkyong.core;
import java.util.ArrayList;
import java.util.List;
public class User {
	private int age = 29;
	private String name = "mkyong";
	private List<String> messages = new ArrayList<String>() {
			add("msg 1");
			add("msg 2");
			add("msg 3");
	//getter and setter methods
	public String toString() {
		return "User [age=" + age + ", name=" + name + ", " +
				"messages=" + messages + "]";

3. Java Object to JSON

Convert an “user” object into JSON formatted string, and save it into a file “user.json“.

package com.mkyong.core;
import org.codehaus.jackson.JsonGenerationException;
public class JacksonExample {
    public static void main(String[] args) {
	User user = new User();
	ObjectMapper mapper = new ObjectMapper();
	try {
		// convert user object to json string, and save to a file
		mapper.writeValue(new File("c:\\user.json"), user);
		// display to console
	} catch (JsonGenerationException e) {
	} catch (JsonMappingException e) {
	} catch (IOException e) {


{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
Above JSON output is hard to read. You can enhance it by enable the pretty print feature.

4. JSON to Java Object

Read JSON string from file “user.json“, and convert it back to Java object.

package com.mkyong.core;
import org.codehaus.jackson.JsonGenerationException;
public class JacksonExample {
    public static void main(String[] args) {
	ObjectMapper mapper = new ObjectMapper();
	try {
		// read from file, convert it to user class
		User user = mapper.readValue(new File("c:\\user.json"), User.class);
		// display to console
	} catch (JsonGenerationException e) {
	} catch (JsonMappingException e) {
	} catch (IOException e) {
User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]


  1. Download Jackson
  2. Jackson Official Site
  3. Gson example – convert Java object to / from JSON
Tags :

About the Author

Founder of and, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.


  • Pingback: how to become an electrician in california()

  • Pingback: level 3 electrician()

  • Pingback: house blue()

  • Pingback: zak?ad szklarski piotrków trybunalski()

  • Pingback: alkaline water brands()

  • Pingback: plumbing parts kohler()

  • Pingback: destin locksmithing santa rosa beach()

  • Pingback: locksmith rapper()

  • Pingback: more about the author()

  • Pingback: electrician license pa()

  • Pingback: pay day loans()

  • Pingback: paypal loans()

  • Pingback: water ionizer()

  • Pingback: water ionizer()

  • Pingback: laan penge billigt()

  • Pingback: stop parking()

  • Pingback: bedste laan lige nu()

  • Pingback: mobile porn()

  • Pingback: penge lan nu()

  • Pingback: car parking()

  • Pingback: Direct TV()

  • Pingback: Blue Coaster33()

  • vaibhav

    I m getting following error while running.. No serializer found for class rough.User and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )
    at rough.json2.main(

  • aniket

    Thank you for the examples. I wanted to know how do you verify the fields in the deserialized object i.e. the Java object obtained from JSON is valid. i.e I want to verify that all the fields in the Java obejct are the same from the JSON response. Do I have to do some kind of depth first search on the object since it can be nested too. Any pointers would be helpful

  • Imtiazahmad007

    The above is a great example of serializing and deserializing one user object in json format. But how can I deserialize a list of user objects? I want to deserialize a list of pojos.

    Thank you for any help you can provide quickly.

  • java

    org.codehaus.jackson.JsonParseException: Unexpected character (‘c’ (code 99)): expected a valid value (number, String, array, object, ‘true’, ‘false’ or ‘null’)
    at [Source:; line: 1, column: 2]
    at org.codehaus.jackson.JsonParser._constructError(
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(
    at org.codehaus.jackson.impl.ReaderBasedParser._handleUnexpectedValue(
    at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(
    at jackson.Save.main(


      What is this?????

  • Ricky manhotra

    i am trying taking inputs from CMD, i need to convert those inputs to java pojo using apache.commons.BeanUtils using setproperty method, and eventually convert that pojo into java string using jackson library’s ObjectMapper writeValueAsString method. Help me..!!!

  • Luis

    Easy and with immediate effect,thank you very much :)

  • Ganesh Gowtham

    Hey ,

    You dont need to use GSON just for formatting.

    Jackson api has a feature .

    mapper.configure(SerializationConfig.Feature.INDENT_OUTPUT, true);

    Ganesh Gowtham

  • Gaurav

    Really helpful Mkyong.
    I think this can also be done using Gson. Makes it quite easy to serialize/deserialize POJOs into JSON strings.

  • Pingback: Parsing JSON W/ API Key : Android Community - For Application Development()

  • Pingback: how to read data from json url in java? | BlogoSfera()

  • Pingback: Android – Dowload json data from URL : Android Community - For Application Development()

  • Pingback: Using Jackson 2.x for JSON in Java | Adventures in tech()

  • Swapnil Dhawad

    I just want to return JSON as output parameter form my webservice method but jax-rs bottom up webservice not allowing me to do so…please guide me how to return json from webservice method

  • Pingback: Create Object vs Reading Json : Android Community - For Application Development()

  • sumit

    Dear M.K.Yong,

    Could you plzz let me know how to convert csv/excel file data to json format??

    I tried so hard but didn’t find any solution.If you will help me it would be appreciable.

    Thanks & Regards,
    Sumit Ranjan

  • Leonardo

    When I use:

    objectMapper.readValue(json, targetClass);

    And there is some characters with pontuation like “Não” readValue transform to something like: “NÃ&O”

    I thing the throuble is about UTF8 decode. Can you help-me?

  • murkein

    Excellent :)

  • shankar

    Is there any way to do WITHOUT FILE, writing to and reading from a file is very expensive.

    • Christophe


      Here is an example of POJO initialization from JSON String:

      // file

      package myTest;
      import javax.xml.bind.annotation.XmlRootElement;

      public class Pojo {
      private String id;

      public String getId() {
      return id;

      public void setId(String id) { = id;

      public Pojo() {

      Test Java file extract:


      ObjectMapper mapper = new ObjectMapper();
      String json = “{\”id\”:\”123\”}”;
      Pojo pojo = mapper.readValue(json, Pojo.class);

  • Anuj


    I wrote REST Service using CXF and Spring. Service is returning output in xml when using MediaType.APPLICATION_XML but i want to return output as JSON and not XML. I found that instead of just using @Produces({ @application/json }), there are some JSONProvider needs to be used in Spring Configuration. I don’t want to use CXF Jettison but needs to use “Jackson”. can you please assist on below?

    @Produces({ MediaType.APPLICATION_JSON})
    public Customer getAllCustomers() {
    return customers; //customers is Array list of Customer

  • Yogesh


    I have some string variables and I need to create JSON object from them and return JSON Object from my function. I need to use jackson json library for project requirements. Can you please tell how to return a json object and not write to a file.

    Map&lt;String, String&gt; resultData = new HashMap&lt;String, String&gt;();
    					resultData.put(&quot;id&quot;, id);
    					resultData.put(&quot;Name&quot;, Name);
    					resultData.put(&quot;dob&quot;, dob);
    					resultData.put(&quot;gender&quot;, gender);
    					ObjectMapper mapper = new ObjectMapper();
  • Sidhardh No serializer found for class edu.learning.json.json_examples.User and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationConfig.Feature.FAIL_ON_EMPTY_BEANS) )

    I’m getting the above exception while executing objectmapper.writeValue. How to solve this

    • Faisal

      Although I am new with JSON but may be the following findings will help.

      I was having the same issue and then resolved that by adding JSON Annotation with the POJO called “”. You need to add “@JsonAutoDetect” just infront of your “public class User{…” declaration and “@JsonProperty” infront of any attributes (here it is: private int age = 29; and private String name = “mkyong”;) and methods (here it is: private List messages = new ArrayList() {…).

      Note that what ever element/information you wanna pass to your main Java Class (here it is “public class JacksonExample{…”) from the POJO, add the proper JSON Annotation.

    • Pulkit Singhal

      You actually need to disable the empty bean failure behaviour. It is not exactly simple to pass Jackson configuration through Jersey but its relatively easy after 15~20 mins of trying.

      This link:
      talks about configuring Jackson for Jersey:

      “Jackson JSON processor could be futher controlled via providing custom Jackson ObjectMapper instance. This could be handy if you need to redefine the default Jackson behaviour and to fine-tune how your JSON data structures look like. Detailed description of all Jackson features is out of scope of this guide. The example bellow gives you a hint on how to wire your ObjectMapper instance into your Jersey application.”

      Download to get a complete example using POJO based JSON support.

    • acdcjunior

      Just create the getters and setters.

    • jisong wu

      please change the “private” to “public” in front of each properties of, i think it is the simplest solution to solve this problem
      public class User{
      public int age = 29;
      public String name =”mkYong”;
      public List messages =………….

      but i don’t think it violate coding standard, because it let these properties value can be changed arbitrarily from outside, so it is dangerous, so i recommend you to do like this:

      public class User {
      private int age = 29;
      private String name = “mkyong”;
      private List messages = …

      • Sushant

        Thanks jisong for your inputs on solving this issue.

  • C

    To make this work with the latest (1.9.3) Jackson, there must be getters and setters for the members in the User class.

  • Pingback: Java JSON Tutorial()

  • Pingback: How to convert Java Map to / from JSON (Jackson)()

  • Pingback: Jackson Streaming API to read and write JSON()

  • Pingback: Jackson Tree Model Example()

  • Pingback: How to enable pretty print JSON output (Jackson)()