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

In this tutorial, we show you how to use Jackson 1.x data binding to convert Java object to / from JSON.

Note
Jackson 1.x is a maintenance project, please use Jackson 2.x instead.
Note
This tutorial is obsolete, no more update, please refer to the latest Jackson 2 tutorial – Object to / from JSON.

1. Quick Reference

1.1 Convert Java object to JSON, writeValue(...)


ObjectMapper mapper = new ObjectMapper();
User user = new User();

//Object to JSON in file
mapper.writeValue(new File("c:\\user.json"), user);

//Object to JSON in String
String jsonInString = mapper.writeValueAsString(user);

1.2 Convert JSON to Java object, readValue(...)


ObjectMapper mapper = new ObjectMapper();
String jsonInString = "{'name' : 'mkyong'}";

//JSON from file to Object
User user = mapper.readValue(new File("c:\\user.json"), User.class);

//JSON from String to Object
User user = mapper.readValue(jsonInString, User.class);

P.S All examples are tested with Jackson 1.9.13

2. Jackson Dependency

For Jackson 1.x, it contains 6 separate jars for different purpose, in most cases, you just need jackson-mapper-asl.

pom.xml

	<dependency>
		<groupId>org.codehaus.jackson</groupId>
		<artifactId>jackson-mapper-asl</artifactId>
		<version>1.9.13</version>
	</dependency>

3. POJO (Plain Old Java Object)

An User object for testing.

User.java

package com.mkyong.json;

import java.util.List;

public class User {

	private String name;
	private int age;
	private List<String> messages;

	//getters and setters
}

4. Java Object to JSON

Convert an user object into a JSON formatted string.

JacksonExample.java

package com.mkyong.json;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

		//For testing
		User user = createDummyUser();
		
		try {
			//Convert object to JSON string and save into file directly 
			mapper.writeValue(new File("D:\\user.json"), user);
			
			//Convert object to JSON string
			String jsonInString = mapper.writeValueAsString(user);
			System.out.println(jsonInString);
			
			//Convert object to JSON string and pretty print
			jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(user);
			System.out.println(jsonInString);
			
			
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	private static User createDummyUser(){
		
		User user = new User();
		
		user.setName("mkyong");
		user.setAge(33);

		List<String> msg = new ArrayList<>();
		msg.add("hello jackson 1");
		msg.add("hello jackson 2");
		msg.add("hello jackson 3");

		user.setMessages(msg);
		
		return user;
		
	}
}

Output


//new json file is created in D:\\user.json"

{"name":"mkyong","age":33,"messages":["hello jackson 1","hello jackson 2","hello jackson 3"]}

{
  "name" : "mkyong",
  "age" : 33,
  "messages" : [ "hello jackson 1", "hello jackson 2", "hello jackson 3" ]
}

5. JSON to Java Object

Read JSON string and convert it back to a Java object.

JacksonExample.java

package com.mkyong.json;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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 {

			// Convert JSON string from file to Object
			User user = mapper.readValue(new File("G:\\user.json"), User.class);
			System.out.println(user);

			// Convert JSON string to Object
			String jsonInString = "{\"age\":33,\"messages\":[\"msg 1\",\"msg 2\"],\"name\":\"mkyong\"}";
			User user1 = mapper.readValue(jsonInString, User.class);
			System.out.println(user1);

		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

}

Output


User [name=mkyong, age=33, messages=[hello jackson 1, hello jackson 2, hello jackson 3]]

User [name=mkyong, age=33, messages=[msg 1, msg 2]]

6. @JsonView

@JsonView has been supported in Jackson since version 1.4, it lets you control what fields to display.

6.1 A simple class.

Views.java

package com.mkyong.json;

public class Views {

	public static class NameOnly{};
	public static class AgeAndName extends NameOnly{};

}

6.2 Annotate on the fields you want to display.

User.java

package com.mkyong.json;

import java.util.List;
import org.codehaus.jackson.map.annotate.JsonView;

public class User {

	@JsonView(Views.NameOnly.class)
	private String name;

	@JsonView(Views.AgeAndName.class)
	private int age;
	
	private List<String> messages;

	//getter and setters
}

6.3 Enable the @JsonView via writerWithView().

JacksonExample.java

package com.mkyong.json;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

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

public class JacksonExample {
	public static void main(String[] args) {

		ObjectMapper mapper = new ObjectMapper();
		//By default all fields without explicit view definition are included, disable this
		mapper.configure(SerializationConfig.Feature.DEFAULT_VIEW_INCLUSION, false);
		 
		//For testing
		User user = createDummyUser();
		
		try {
			//display name only
			String jsonInString = mapper.writerWithView(Views.NameOnly.class).writeValueAsString(user);
			System.out.println(jsonInString);
			
			//display namd ana age
			jsonInString = mapper.writerWithView(Views.AgeAndName.class).writeValueAsString(user);
			System.out.println(jsonInString);
			
			
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	
	}

	private static User createDummyUser(){
		
		User user = new User();
		
		user.setName("mkyong");
		user.setAge(33);

		List<String> msg = new ArrayList<>();
		msg.add("hello jackson 1");
		msg.add("hello jackson 2");
		msg.add("hello jackson 3");

		user.setMessages(msg);
		
		return user;
		
	}
}

Output


{"name":"mkyong"}
{"name":"mkyong","age":33}

References

  1. Jackson Project Home @github
  2. Gson – Convert Java object to / from JSON

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar
47 Comment threads
17 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
47 Comment authors
yogesh indaniChetan Rajzahra khoobiTutorials To Learnchandu Recent comment authors
newest oldest most voted
chandu
Guest
chandu

Hi

In fortify scan am getting following error

writes unvalidated input into JSON. This call could allow an attacker to inject arbitrary elements or attributes into the JSON entity.

can any one know the solution for this problem please help me. Am stuck with this problem

// Convert JSON string to Object
String jsonInString = “{“age”:33,”messages”:[“msg 1″,”msg 2″],”name”:”mkyong”}”;
User user1 = mapper.readValue(jsonInString, User.class);
System.out.println(user1);
Thanks
chandu

yash pgdost
Guest
yash pgdost

Really helpful, Thanks..!

yash pgdost
Guest
yash pgdost

Thanks, It helped!

trackback
How to enable pretty print JSON output (Jackson)

[…] mkyongprintIt’s easy to enable pretty print JSON output in Jackson framework. Take last object to/from json example : User user = new User(); ObjectMapper mapper = new ObjectMapper(); […]

trackback
Jackson Tree Model Example

[…] In this tutorial, the file “file.json” (which is generated from last Jackson data binding example) will be reused. This time, we show you how to read the JSON string from “file.json” […]

trackback
Jackson Streaming API to read and write JSON

[…] summary, for performance critical application, use Steaming API, otherwise, just use normal Jackson data binding.ReferencesJackson Streaming API documentationJackson Streaming API short example […]

trackback
How to convert Java Map to / from JSON (Jackson)

[…] JSON (Jackson) Published: August 11, 2011 , Updated: August 11, 2011 , Author: mkyongprintIn last Jackson example, we show you how to convert user define object to / from JSON data. This time, we are doing the […]

trackback
Java JSON Tutorial

[…] are Jackson, Google Gson and JSON.simpleHappy learning ~JacksonA High-performance JSON processor.Jackson data binding example – Object & JSON Example to use ObjectMapper writeValue() and readValue() to convert Java object to / from […]

C
Guest
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.

Sidhardh
Guest
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

Faisal
Guest
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,… Read more »

Pulkit Singhal
Guest
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… Read more »

acdcjunior
Guest
acdcjunior

Just create the getters and setters.

jisong wu
Guest
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
Guest
Sushant

Thanks jisong for your inputs on solving this issue.

Yogesh
Guest
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<String, String> resultData = new HashMap<String, String>();
					resultData.put("id", id);
					resultData.put("Name", Name);
					resultData.put("dob", dob);
					resultData.put("gender", gender);
										
					ObjectMapper mapper = new ObjectMapper();
					mapper.writeValueAsString(writeData);
					
Anuj
Guest
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
}

shankar
Guest
shankar

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

Christophe
Guest
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());

murkein
Guest
murkein

Excellent 🙂

Leonardo
Guest
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?

sumit
Guest
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

trackback
Create Object vs Reading Json : Android Community - For Application Development

[…] Use objects. I would suggest to use Jackson library, be cause it is very fast and easy to ingrate. You can find code examples here : http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ […]

Swapnil Dhawad
Guest
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

trackback
Using Jackson 2.x for JSON in Java | Adventures in tech

[…] MKyong.com’s always useful tutorials to topics. […]

trackback
Android – Dowload json data from URL : Android Community - For Application Development

[…] that, I ‘d suggest using Jakson library to create a class from the received json object. here is an example of how to use Jakson […]

trackback
how to read data from json url in java? | BlogoSfera

[…] I came across the following tutorial: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ […]

trackback
Parsing JSON W/ API Key : Android Community - For Application Development

[…] I recomment you use a library like Jackcon: http://www.mkyong.com/java/how-to-convert-java-object-to-from-json-jackson/ […]

Gaurav
Guest
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

Ganesh Gowtham
Guest
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/

Luis
Guest
Luis

Easy and with immediate effect,thank you very much 🙂

Ricky manhotra
Guest
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..!!!

java
Guest
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
Guest
Asp.net

What is this?????

python
Guest
python

I have no idea

Imtiazahmad007
Guest
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.

mkyong
Guest
mkyong


String json = "[{"name":"mkyong"}, {"name":"laplap"}]";
List list = mapper.readValue(json, new TypeReference<List>(){});

aniket
Guest
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

Ranish
Guest
Ranish

I need to convert a jason file similar to [{“age”:29,”,”name”:”mkyong”},{“age”:35,”,”name”:”Tom”}]. Assume I have a User class. I’m referring to above 4th example (Jason to Java Object). Can I create ArrayList of User objects? Pls give me a code sample.

mkyong
Guest
mkyong

Refer to this Jackson 2 example – Step 7
http://www.mkyong.com/java/jackson-2-convert-java-object-to-from-json/

List list = mapper.readValue(json, new TypeReference<List>(){});