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, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

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

zahra khoobi
Guest
zahra khoobi

thanks!
your samples often help me to understand things at short time!

Tutorials To Learn
Guest
Tutorials To Learn

I covert convert json back to list error;

run:
{“firstName”:”Mike”,”lastName”:”harvey1″,”age”:34,”contact”:”001894536″}
org.codehaus.jackson.map.JsonMappingException: No suitable constructor found for type [simple type, class gson.Main$Person]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: java.io.StringReader@146ba0ac; line: 1, column: 2]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObjectUsingNonDefault(BeanDeserializer.java:740)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:683)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2723)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1854)
at gson.Main.main(Main.java:47)
BUILD SUCCESSFUL (total time: 0 seconds)

chaitanya
Guest
chaitanya

i am try the above code but i end up with this error all the time

chaitanya
Guest
chaitanya

org.codehaus.jackson.map.JsonMappingException: Can not instantiate value of type [simple type, class com.util.Docker_Sims] from JSON String; no single-String constructor/factory method
at org.codehaus.jackson.map.deser.std.StdValueInstantiator._createFromStringFallbacks(StdValueInstantiator.java:379)
at org.codehaus.jackson.map.deser.std.StdValueInstantiator.createFromString(StdValueInstantiator.java:268)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromString(BeanDeserializer.java:765)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:585)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1817)
at com.util.DBUtil.main(DBUtil.java:43)

fabrice
Guest
fabrice

Hello. Great, thanks,
But how to parse a JSon String that starts with a “prefix” like:

{“record”:{“name”:”mkyong”}}

The ObjectMapper.readValue(string, User.class) will certainly fail.
Any idea ?

Thanks !
Fabrice

Chetan Raj
Guest
Chetan Raj

That is object in object , one way would be to create two class one for inner object(“name”…..), and another for “record”. and initializing those variables

Heinrich Goebl
Guest
Heinrich Goebl

Thanks a lot – awesome like always!
package of artifact has changed: groupId: com.fasterxml.jackson.core, artifactId: jackson-databind

Heinrich Goebl
Guest
Heinrich Goebl

Sorry, haven’t seen Note at the top.

amit kumar
Guest
amit kumar

I have written webservies in java after when i heat the url username and password then that he is return only two value or remaining value is null how can solve this problem plz anybody help me sir…

Anonymous
Guest
Anonymous

Please teach me to “heat” the url. BBQ?!

amit kumar
Guest
amit kumar

Hi Sir,

I have written webservies in java after that he is return only two value or remaining value is null how can solve this problem plz anybody help me sir…

Bruno Freitas
Guest
Bruno Freitas

Thanks man.

abu sayed
Guest
abu sayed

Hi Mr. Mkyong, thanks for your tutorial. Can you give real scenarios in software where it is necessary serialization to convert Object to Json or Json to object ?

trackback
Jackson 2 – Convert Java Object to / from JSON

[…] Jackson 1.x – Object to JSON […]

Maruthi
Guest
Maruthi

As always – saved my day. Thanks

Tapishnu Sengupta
Guest
Tapishnu Sengupta

Hi can anyone tell me how to convert java object to xml using jackson?

sudheer
Guest
sudheer

add jackson mappeer jar to it and try again

raga
Guest
raga

hi mkyong i am fan of u i am reading ur tutorials it is very helpful to me

Ryan
Guest
Ryan

as always. thanks :)

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

vaibhav
Guest
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)

simpleJack
Guest
simpleJack

Add getters and setters on the User and make it implement Serializable

Selvin
Guest
Selvin

Add this line, if you are using Jackson 1.9 or above.
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);

mkyong
Guest
mkyong

Fixed, articled is updated to Jackson 1.9.x

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

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

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

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

Luis
Guest
Luis

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

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/

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

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/ […]

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/ […]