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);
Note
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

  <repositories>
	<repository>
		<id>codehaus</id>
		<url>http://repository.codehaus.org/org/codehaus</url>
	</repository>
  </repositories>
 
  <dependencies>
	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.8.5</version>
	</dependency>
  </dependencies>

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

2. POJO

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
 
	@Override
	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 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 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
		System.out.println(mapper.writeValueAsString(user));
 
	} catch (JsonGenerationException e) {
 
		e.printStackTrace();
 
	} catch (JsonMappingException e) {
 
		e.printStackTrace();
 
	} catch (IOException e) {
 
		e.printStackTrace();
 
	}
 
  }
 
}

Output

{"age":29,"messages":["msg 1","msg 2","msg 3"],"name":"mkyong"}
Note
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 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 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
		System.out.println(user);
 
	} catch (JsonGenerationException e) {
 
		e.printStackTrace();
 
	} catch (JsonMappingException e) {
 
		e.printStackTrace();
 
	} catch (IOException e) {
 
		e.printStackTrace();
 
	}
 
  }
 
}
User [age=29, name=mkyong, messages=[msg 1, msg 2, msg 3]]

References

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

About the Author

mkyong
Founder of Mkyong.com and HostingCompass.com, 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.

Comments

  • 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..

    org.codehaus.jackson.map.JsonMappingException: 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 org.codehaus.jackson.map.ser.impl.UnknownSerializer.failForEmpty(UnknownSerializer.java:52)
    at org.codehaus.jackson.map.ser.impl.UnknownSerializer.serialize(UnknownSerializer.java:25)
    at org.codehaus.jackson.map.ser.StdSerializerProvider._serializeValue(StdSerializerProvider.java:610)
    at org.codehaus.jackson.map.ser.StdSerializerProvider.serializeValue(StdSerializerProvider.java:256)
    at org.codehaus.jackson.map.ObjectMapper._configAndWriteValue(ObjectMapper.java:2575)
    at org.codehaus.jackson.map.ObjectMapper.writeValue(ObjectMapper.java:2048)
    at rough.json2.main(json2.java:29)

  • aniket

    Hi,
    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: java.io.StringReader@12152e6; line: 1, column: 2]
    at org.codehaus.jackson.JsonParser._constructError(JsonParser.java:1213)
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportError(JsonParserMinimalBase.java:375)
    at org.codehaus.jackson.impl.JsonParserMinimalBase._reportUnexpectedChar(JsonParserMinimalBase.java:306)
    at org.codehaus.jackson.impl.ReaderBasedParser._handleUnexpectedValue(ReaderBasedParser.java:599)
    at org.codehaus.jackson.impl.ReaderBasedParser.nextToken(ReaderBasedParser.java:362)
    at org.codehaus.jackson.map.ObjectMapper._initForReading(ObjectMapper.java:2168)
    at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2125)
    at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1395)
    at jackson.Save.main(Save.java:53)
    null

    • Asp.net

      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 :)

  • https://sites.google.com/site/ganeshgowtham/ 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
    https://sites.google.com/site/ganeshgowtham/

  • http://atechiediary.blogspot.in/2013/06/javajsextjs-convert-serialize-java.html Gaurav

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

    http://atechiediary.blogspot.in/2013/06/javajsextjs-convert-serialize-java.html

  • 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

  • http://androiddevbr.wordpress.com/ 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

      Shankar,

      Here is an example of POJO initialization from JSON String:

      // Pojo.java file

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

      @XmlRootElement
      public class Pojo {
      private String id;

      public String getId() {
      return id;
      }

      public void setId(String id) {
      this.id = id;
      }

      public Pojo() {
      }
      }

      Test Java file extract:

      import org.codehaus.jackson.map.ObjectMapper;

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

  • Anuj

    Hi,

    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?

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

  • Yogesh

    Hi

    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();
    					mapper.writeValueAsString(writeData);
  • Sidhardh

    org.codehaus.jackson.map.JsonMappingException: 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

    • http://faisalnet5.blogspot.com/ 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 “User.java”. 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.

    • http://pulkitsinghal.blogspot.com 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:
      http://jersey.java.net/nonav/documentation/latest/json.html
      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 https://maven.java.net/service/local/artifact/maven/redirect?r=releases&g=com.sun.jersey.samples&a=jacksonjsonprovider&v=1.13&c=project&e=zip 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 User.java, i think it is the simplest solution to solve this problem
      like:
      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:

      @JsonAutoDetect
      public class User {
      @JsonProperty
      private int age = 29;
      @JsonProperty
      private String name = “mkyong”;
      @JsonProperty
      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)()