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

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
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
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?
Excellent :)
Is there any way to do WITHOUT FILE, writing to and reading from a file is very expensive.
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
}
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.
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
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.
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.
Just create the getters and setters.
To make this work with the latest (1.9.3) Jackson, there must be getters and setters for the members in the User class.