Jackson 2 – Convert Java Object to / from JSON

In this tutorial, we will show you how to use Jackson 2.x to convert Java object to / from JSON.

1. Quick Reference

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


ObjectMapper mapper = new ObjectMapper();
Staff obj = new Staff();

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

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

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


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

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

//JSON from URL to Object
Staff obj = mapper.readValue(new URL("http://mkyong.com/api/staff.json"), Staff.class);

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

P.S All examples are tested with Jackson 2.6.3

Differences from Jackson 1.x
Most of the APIs still maintains the same method name and signature, just the packaging is different.

  1. Jackson 1.x – org.codehaus.jackson.map
  2. Jackson 2.x – com.fasterxml.jackson.databind

2. Jackson 2 Dependency

2.1 For Jackson 2.x, declares jackson-databind, it will download its dependencies – jackson-core and jackson-annotations

pom.xml

	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>2.6.3</version>
	</dependency>

2.2 Review the Jackson dependencies :

mvn dependency:tree

[INFO] com.mkyong:json:jar:0.0.1-SNAPSHOT
[INFO] +- com.fasterxml.jackson.core:jackson-databind:jar:2.6.3:compile
[INFO] |  +- com.fasterxml.jackson.core:jackson-annotations:jar:2.6.0:compile
[INFO] |  \- com.fasterxml.jackson.core:jackson-core:jar:2.6.3:compile
[INFO] \- junit:junit:jar:3.8.1:test

3. POJO (Plain Old Java Object)

A simple pojo Staff object for testing.

Staff.java

package com.mkyong.json;

import java.math.BigDecimal;
import java.util.List;

public class Staff {

	private String name;
	private int age;
	private String position;
	private BigDecimal salary;
	private List<String> skills;

	//getters and setters

4. Java Object to JSON

Convert a Staff object into a JSON formatted string.

Jackson2Example.java

package com.mkyong.json;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

	public static void main(String[] args) {
		Jackson2Example obj = new Jackson2Example();
		obj.run();
	}

	private void run() {
		ObjectMapper mapper = new ObjectMapper();

		Staff staff = createDummyObject();

		try {
			// Convert object to JSON string and save into a file directly
			mapper.writeValue(new File("D:\\staff.json"), staff);

			// Convert object to JSON string
			String jsonInString = mapper.writeValueAsString(staff);
			System.out.println(jsonInString);

			// Convert object to JSON string and pretty print
			jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);
			System.out.println(jsonInString);

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

	private Staff createDummyObject() {

		Staff staff = new Staff();

		staff.setName("mkyong");
		staff.setAge(33);
		staff.setPosition("Developer");
		staff.setSalary(new BigDecimal("7500"));

		List<String> skills = new ArrayList<>();
		skills.add("java");
		skills.add("python");

		staff.setSkills(skills);

		return staff;

	}

}

Output


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

{"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}

{
  "name" : "mkyong",
  "age" : 33,
  "position" : "Developer",
  "salary" : 7500,
  "skills" : [ "java", "python" ]
}

5. JSON to Java Object

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

Jackson2Example.java

package com.mkyong.json;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

	public static void main(String[] args) {
		Jackson2Example obj = new Jackson2Example();
		obj.run();
	}

	private void run() {
		ObjectMapper mapper = new ObjectMapper();

		try {

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

			// Convert JSON string to Object
			String jsonInString = "{\"name\":\"mkyong\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
			Staff staff1 = mapper.readValue(jsonInString, Staff.class);
			System.out.println(staff1);

			//Pretty print
			String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff1);
			System.out.println(prettyStaff1);
			
		} catch (JsonGenerationException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}

Output


Staff [name=mkyong, age=33, position=Developer, salary=7500, skills=[java, python]]

Staff [name=mkyong, age=0, position=null, salary=7500, skills=[java, python]]

{
  "name" : "mkyong",
  "age" : 0,
  "position" : null,
  "salary" : 7500,
  "skills" : [ "java", "python" ]
}

6. @JsonView

@JsonView, useful feature, it lets you control what fields to display.

6.1 A simple class, do nothing, just define two views (static classes as members).

Views.java

package com.mkyong.json;

public class Views {

	public static class Normal{};
	
	public static class Manager extends Normal{};

}

6.2 For “Normal view”, salary will be hidden, for “Manager view”, display everything.

Staff.java

package com.mkyong.json;

import java.math.BigDecimal;
import java.util.List;
import com.fasterxml.jackson.annotation.JsonView;

public class Staff {

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

	@JsonView(Views.Normal.class)
	private int age;

	@JsonView(Views.Normal.class)
	private String position;

	@JsonView(Views.Manager.class)
	private BigDecimal salary;

	@JsonView(Views.Normal.class)
	private List<String> skills;

6.3 To enable the @JsonView features, use the following methods :

  1. mapper.writerWithView(“view class”).writeValue()
  2. mapper.readerWithView(“view class”).readValue()
JacksonExample.java

package com.mkyong.json;

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

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

public class Jackson2Example {

	public static void main(String[] args) {
		Jackson2Example obj = new Jackson2Example();
		obj.run();
	}

	private void run() {
		ObjectMapper mapper = new ObjectMapper();

		Staff staff = createDummyObject();

		try {

			// Salary will be hidden
			System.out.println("Normal View");
			String normalView = mapper.writerWithView(Views.Normal.class).writeValueAsString(staff);
			System.out.println(normalView);

			String jsonInString = "{\"name\":\"mkyong\",\"age\":33,\"position\":\"Developer\",\"salary\":7500,\"skills\":[\"java\",\"python\"]}";
			Staff normalStaff = mapper.readerWithView(Views.Normal.class).forType(Staff.class).readValue(jsonInString);
			System.out.println(normalStaff);

			// Display everything
			System.out.println("\nManager View");
			String managerView = mapper.writerWithView(Views.Manager.class).writeValueAsString(staff);
			System.out.println(managerView);

			Staff managerStaff = mapper.readerWithView(Views.Manager.class).forType(Staff.class).readValue(jsonInString);
			System.out.println(managerStaff);

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

	private Staff createDummyObject() {

		Staff staff = new Staff();

		staff.setName("mkyong");
		staff.setAge(33);
		staff.setPosition("Developer");
		staff.setSalary(new BigDecimal("7500"));

		List<String> skills = new ArrayList<>();
		skills.add("java");
		skills.add("python");

		staff.setSkills(skills);

		return staff;

	}

}

Output


Normal View
{"name":"mkyong","age":33,"position":"Developer","skills":["java","python"]}
Staff [name=mkyong, age=33, position=Developer, salary=null, skills=[java, python]]

Manager View
{"name":"mkyong","age":33,"position":"Developer","salary":7500,"skills":["java","python"]}
Staff [name=mkyong, age=33, position=Developer, salary=7500, skills=[java, python]]
Note
Read this Spring MVC Ajax example – This example demonstrate the use of @JsonView on Spring MVC framework.

7. Misc Examples

Some commonly ask questions.

7.1 Convert a JSON Array format to a Java List object.


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

7.2 Convert a JSON to a Map


	String json = "{\"name\":\"mkyong\", \"age\":33}";
	Map<String, Object> map = mapper.readValue(json, new TypeReference<Map<String,Object>>(){});

7.3 How to create or update a JsonNode?
Answer : Read this Jackson TreeModel example

References

  1. Jackson databind examples
  2. Jackson Project Home @github
  3. Gson – Convert Java object to / from JSON
  4. Jackson 1.x – Object to JSON
  5. Jackson 2.x – Create or Update a JsonNode

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
Jon Rodriguez Breton
Guest
Jon Rodriguez Breton
Dear Mkyong, I found your tutorial very helpful. Sadly, I’ve a problem. At the moment I use the mapper to convert the object into a String, for some reason it adds a extra field called “map” to my JSON: { “A”: [ { “map”: { “B”: “X”, “C”: “Y”, “D”: “Z”, “E”: “F” } }, { “map”: { “B”: “X”, “C”: “Y”, “D”: “Z”, “E”: “F” } } ] } I’m converting an object of JSONObjects into a JSON. Can you help me please? Thanks!
sham
Guest
sham

One thing I want to highlight here; which can be useful for some one else.
We should create instance of an ObjectMapper only once(constructor); Creating it every time locally required additional overhead which hampers application performance.

Roger Ng
Guest
Roger Ng

Is there a way change the data type and value of a variable from Java object to JSON?
For example, there is a Long data type variable storing the value of money. It is supposed to be divided by 100 in the JSON output.
Java object (Long): 630
JSON output (double): 6.30

Paulo Gomes
Guest
Paulo Gomes

Ă“tima postagem, me ajudou muito. Obrigado.

innuendo
Guest
innuendo

Hi Mkyong, first of all thank you so much for producing top quality materials and tutorials, so much appreciated. I am struggling to make your example to work with a number of XML that I previously parsed using JAXB and converted into a java object with only a subset of elements from the original .xml file. I like the createDummyObject() implementation, but it holds hardcoded values. Can you point me to a more dynamic solution? Thank you so much! I.

Janardhan
Guest
Janardhan

Hi Mykong good noon,

I want one clarification about iso date conversion , from rest service we are receiving the ISO Date in String format for example ‘2015-11-30T11:22:28.9368198Z’ and jackson mapper is convertion iso Date String to date , here am facing the problem it is returin different results, can you please how to convert ISO Date String into Data in java

trackback
Convert JSON string to Map – Jackson

[…] Jackson 2 – Convert Java Object to / from JSONJava – Check if key exists in HashMapjQuery loop over JSON string – $.each exampleHow to access JSON object in JavaScriptJackson : was expecting double-quote to start field name […]

trackback
Jackson Tree Model Example

[…] Jackson 2 – Convert Java Object to / from JSONjQuery loop over JSON string – $.each exampleHow to access JSON object in JavaScriptJackson : was expecting double-quote to start field name Java JSON Tutorial […]

Rich Striker
Guest
Rich Striker

You do not show converting a List of OBJECTS to JSON….fail.

Smitha242
Guest
Smitha242

I gotta preferred this web web page it appears very valuable quite advantageous kfkaeeeedegffdfa