Main Tutorials

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 Author

author image
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

Subscribe
Notify of
55 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
yash pgdost
8 years ago

Really helpful, Thanks..!

chandu
6 years ago

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

chaitanya
6 years ago

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

yash pgdost
8 years ago

Thanks, It helped!

Rani
2 years ago

Very nice

Sanjeev Kumar
3 years ago

Very nice tutorial

zahra khoobi
6 years ago

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

Tutorials To Learn
6 years ago

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
6 years ago

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
6 years ago

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
5 years ago
Reply to  fabrice

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

amit kumar
6 years ago

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
6 years ago
Reply to  amit kumar

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

amit kumar
6 years ago

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
7 years ago

Thanks man.

abu sayed
7 years ago

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 ?

Maruthi
8 years ago

As always – saved my day. Thanks

Tapishnu Sengupta
8 years ago

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

sudheer
9 years ago

add jackson mappeer jar to it and try again

raga
9 years ago

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

Ryan
9 years ago

as always. thanks 🙂

Ranish
10 years ago

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
8 years ago
Reply to  Ranish

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

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

aniket
10 years ago

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
10 years ago

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
8 years ago
Reply to  Imtiazahmad007


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

java
10 years ago

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
10 years ago
Reply to  java

What is this?????

python
8 years ago
Reply to  Asp.net

I have no idea

Ricky manhotra
10 years ago

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
10 years ago

Easy and with immediate effect,thank you very much 🙂

Ganesh Gowtham
10 years ago

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
10 years ago

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

Swapnil Dhawad
11 years ago

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

sumit
11 years ago

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
11 years ago

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?