Main Tutorials

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 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
15 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
rekha
4 years ago

Dear Mkyong,hi how can i convert below json string to object
{
“flightItinerary”: [
{
“price”: {
“includesTax”: true,
“currencyCode”: “KWD”,
“amount”: 78.200135,
“pricePerAdult”: 67.4,
“pricePerChild”: 0,
“pricePerPassenger”: 0,
“totalAmount”: 78.200135,
“totalPricePerAdult”: 77.706,
“totalPricePerChild”: 0,
“totalPricePerPassenger”: 0,
“name”: “Promo”
},
“outboundLeg”: {
“segments”: [
{
“flightClass”: “Economy”,
“flightNumber”: {
“designator”: “SG”,
“number”: ” 14″
},
“DepartureDateTime”: “2019-12-22T01:55:00”,
“ArrivalDateTime”: “2019-12-22T06:25:00”,
“DepartureAirportCode”: “DXB”,
“ArrivalAirportCode”: “BOM”
}
]
},
“inboundLeg”: null,
“Leg1”: null,
“Leg2”: null,
“Leg3”: null,
“Leg4”: null,
“Leg5”: null,
“deeplinkURL”: “https://handoff.wego.com/flights/continue?currency=SAR&url_locale=en&site_code=SA&device_type=desktop&app_type=WEB_APP&domain=sa.wego.com&fare_id=96393e5d1ec79e1a-ap-southeast-1:cleartrip.sa:0&placement_type=metasearch&route=JED-CAI&search_id=96393e5d1ec79e1a-ap-southeast-1&trip_id=cJED:cCAI:2019-11-27&pwa=false&api_version=2&integration_code=cleartrip.com&fare_index=2&total_fares=14&awsalb=qInQlA9JzisLpEc7M5K%2BWhzJsjdzLrxjZee0LnA2qTKaNicLxntSz2X0texziNNWD3odDDNDfY%2BtNWIGbnW6suE1YdryrUQ8Knuwu19seeAt2x1i3g%2FiUBUc5UlM&region=ap-southeast-1&currency_code=SAR&wc=2533a53f-f2ea-4520-9a8a-2e30c98cbce2&ws=02145d96-315b-4104-845c-54992dbe2391&sort=price&order=asc”
},

Jon Rodriguez Breton
7 years ago

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

Is there a way to generate a new class?

Hilton Fernandes
4 months ago

Great content as always. Thanks a lot.

Maxim Verbeeck
2 years ago

is there a way, without using the ObjectMapper, to Map multiple, but specific Json-Objects with different names, which you get thru Rest-API, to an instance of Map<String, Object> map, where string represents the key-name? I was thinking of using JsonAlias annotation first, but I need to be able to differentiate between the Json objects (each has a different name and contains specific search criteria)

seimo
4 years ago

dear mkyong, how to sort the “salary” is :{“2010″:10000,”2012″:12000,”2018”:14000}, but not the “salary”:{“2018″:14000,”2012″:12000,”2010”:10000} ? thx !

Rajesh Varadaraji
5 years ago

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

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

Smitha242
5 years ago

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

sham
6 years ago

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

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

Ótima postagem, me ajudou muito. Obrigado.

innuendo
8 years ago

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

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

Rich Striker
8 years ago

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