Jackson 2 – Convert Java Object to / from JSON

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

1. Basic

1.1 Convert a Staff object to from JSON.

writeValue(...) – Java Objects to JSON


	ObjectMapper mapper = new ObjectMapper();

	// Java object to JSON file
	mapper.writeValue(new File("c:\\test\\staff.json"), new Staff());

	// Java object to JSON string
	String jsonString = mapper.writeValueAsString(object);

readValue(...) – JSON to Java Objects


	ObjectMapper mapper = new ObjectMapper();

	//JSON file to Java object
	Staff obj = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class);

	//JSON URL to Java object
	Staff obj = mapper.readValue(new URL("http://some-domains/api/name.json"), Staff.class);

	//JSON string to Java Object
	Staff obj = mapper.readValue("{'name' : 'mkyong'}", Staff.class);

P.S Tested with Jackson 2.9.8

Note
Read this How to parse JSON with Jackson, containing Jackson examples like Object to/from JSON, @JsonView, @JsonProperty, @JsonInclude, @JsonIgnore, and some FAQs.

1. Download Jackson

1.1 Declares jackson-databind, it will pull in jackson-annotations and jackson-core

pom.xml

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

1.2 Review the Jackson dependencies :

Terminal

$ mvn dependency:tree

\- com.fasterxml.jackson.core:jackson-databind:jar:2.9.8:compile
[INFO]    +- com.fasterxml.jackson.core:jackson-annotations:jar:2.9.0:compile
[INFO]    \- com.fasterxml.jackson.core:jackson-core:jar:2.9.8:compile
Difference between Jackson 1 and Jackson 2
Most of the APIs still maintains the same method name and signature, just the packaging is different.

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

2. POJO

A simple Java object for testing.

Staff.java

public class Staff {

    private String name;
    private int age;
    private String[] position;              //  Array
    private List<String> skills;            //  List
    private Map<String, BigDecimal> salary; //  Map

	// getters , setters, some boring stuff
}

3. Java Objects to JSON

JacksonExample1.java

package com.mkyong;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class JacksonExample1 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        Staff staff = createStaff();

        try {

            // Java objects to JSON file
            mapper.writeValue(new File("c:\\test\\staff.json"), staff);

            // Java objects to JSON string - compact-print
            String jsonString = mapper.writeValueAsString(staff);

            System.out.println(jsonString);

            // Java objects to JSON string - pretty-print
            String jsonInString2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff);

            System.out.println(jsonInString2);

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

    }

    private static Staff createStaff() {

        Staff staff = new Staff();

        staff.setName("mkyong");
        staff.setAge(38);
        staff.setPosition(new String[]{"Founder", "CTO", "Writer"});
        Map<String, BigDecimal> salary = new HashMap() {{
            put("2010", new BigDecimal(10000));
            put("2012", new BigDecimal(12000));
            put("2018", new BigDecimal(14000));
        }};
        staff.setSalary(salary);
        staff.setSkills(Arrays.asList("java", "python", "node", "kotlin"));

        return staff;

    }

}

Output

c:\\test\\staff.json

{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"skills":["java","python","node","kotlin"],"salary":{"2018":14000,"2012":12000,"2010":10000}}
Terminal

{"name":"mkyong","age":38,"position":["Founder","CTO","Writer"],"skills":["java","python","node","kotlin"],"salary":{"2018":14000,"2012":12000,"2010":10000}}

{
  "name" : "mkyong",
  "age" : 38,
  "position" : [ "Founder", "CTO", "Writer" ],
  "skills" : [ "java", "python", "node", "kotlin" ],
  "salary" : {
    "2018" : 14000,
    "2012" : 12000,
    "2010" : 10000
  }
}

4. JSON to Java Object

JacksonExample2.java

package com.mkyong;

import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.File;
import java.io.IOException;

public class JacksonExample2 {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        try {

            // JSON file to Java object
            Staff staff = mapper.readValue(new File("c:\\test\\staff.json"), Staff.class);

            // JSON string to Java object
            String jsonInString = "{\"name\":\"mkyong\",\"age\":37,\"skills\":[\"java\",\"python\"]}";
            Staff staff2 = mapper.readValue(jsonInString, Staff.class);

            // compact print
            System.out.println(staff2);

            // pretty print
            String prettyStaff1 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(staff2);

            System.out.println(prettyStaff1);


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

    }

}

Output


Staff{name='mkyong', age=37, position=null, skills=[java, python], salary=null}

{
  "name" : "mkyong",
  "age" : 37,
  "position" : null,
  "skills" : [ "java", "python" ],
  "salary" : null
}
Note
More Jackson examples read this – How to parse JSON with Jackson

References

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
13 Comment threads
0 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
11 Comment authors
Rajesh VaradarajiBRYAN ROMEROMayoSmitha242sham Recent comment authors
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!

BRYAN ROMERO
Guest
BRYAN ROMERO

Is there a way to generate a new class?

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.

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

Rajesh Varadaraji
Guest
Rajesh Varadaraji

Hi Mkyong,
Good read! thanks for the material. Do you know how do we writeValueAsString in UDF 16B so that .net(NewtonSoft Json .Net) de-serialiser can convert this Json back to object.

Mayo
Guest
Mayo

Java Object to JSON – Really Very Helpful this tutorial. Thanks

Smitha242
Guest
Smitha242

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

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.

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