Jackson – How to parse JSON

Jackson provide writeValue() and readValue() methods to convert Java objects to / from JSON.

mapper.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, default compact-print
	String jsonString = mapper.writeValueAsString(new Staff());
	
	// pretty-print
	String jsonString2 = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Staff());

mapper.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/staff.json"), Staff.class);

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

P.S Tested with Jackson 2.9.8

1. Download Jackson

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

2. POJO

A simple Java object, POJO, for testing later.

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
}

5. @JsonProperty – JSON Field Naming

5.1 Default


public class Staff {

    private String name;
	private int age;

Output


{"name":"abc", "age":38}

5.2 Change the property name with @JsonProperty


public class Staff {

    @JsonProperty("custom_name")
    private String name;
	private int age;

Output


{"custom_name":"abc", "age":38}

6. @JsonInclude – Ignore null fields

By default, Jackson will include null fields.


{
  "name" : "mkyong",
  "age" : 38,
  "position" : null,
  "skills" : null,
  "salary" : null
}

6.1 @JsonInclude on class level.

Staff.java

import com.fasterxml.jackson.annotation.JsonInclude;

											//	ignore null fields , class level
@JsonInclude(JsonInclude.Include.NON_NULL) 	//  ignore all null fields
public class Staff {

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

6.2 @JsonInclude on fields level.

Staff.java

import com.fasterxml.jackson.annotation.JsonInclude;

public class Staff {

    private String name;
    private int age;
    
	@JsonInclude(JsonInclude.Include.NON_NULL) //ignore null field on this property only
    private String[] position;              
    
    private List<String> skills;           
	
    private Map<String, BigDecimal> salary;

Output


{
  "name" : "mkyong",
  "age" : 38,
  "skill" : null,
  "salary" : null
}

6.3 Globally.


	ObjectMapper mapper = new ObjectMapper();

	// ignore all null fields globally
	mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

7. @JsonView

7.1 The @JsonView is used to limit fields display for different users. For example:

CompanyViews.java

package com.mkyong;

public class CompanyViews {

    public static class Normal{};

    public static class Manager extends Normal{};
    
}

Normal view only displays name and age, Manager view is able to display all.

Staff.java

import com.fasterxml.jackson.annotation.JsonView;

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

public class Staff {

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

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

    @JsonView(CompanyViews.Manager.class)
    private String[] position;

    @JsonView(CompanyViews.Manager.class)
    private List<String> skills;

    @JsonView(CompanyViews.Manager.class)
    private Map<String, BigDecimal> salary;
JacksonExample.java

package com.mkyong;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

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

public class JacksonExample {

    public static void main(String[] args) {

        ObjectMapper mapper = new ObjectMapper();

        Staff staff = createStaff();

        try {

            // to enable pretty print
            mapper.enable(SerializationFeature.INDENT_OUTPUT);

            // normal
            String normalView = mapper
				.writerWithView(CompanyViews.Normal.class)
				.writeValueAsString(staff);

            System.out.format("Normal views\n%s\n", normalView);

            // manager
            String managerView = mapper
				.writerWithView(CompanyViews.Manager.class)
				.writeValueAsString(staff);

            System.out.format("Manager views\n%s\n", managerView);

        } 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


Normal views
{
  "name" : "mkyong",
  "age" : 38
}

Manager views
{
  "name" : "mkyong",
  "age" : 38,
  "position" : [ "Founder", "CTO", "Writer" ],
  "skills" : [ "java", "python", "node", "kotlin" ],
  "salary" : {
    "2018" : 14000,
    "2012" : 12000,
    "2010" : 10000
  }
}
Note
Read this Jackson @JsonView example

8. @JsonIgnore and @JsonIgnoreProperties

By default, Jackson includes all the fields, even static or transient fields.

8.1 @JsonIgnore to ignore fields on field level.


import com.fasterxml.jackson.annotation.JsonIgnore;

public class Staff {

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

Output


{
  "name" : "mkyong",
  "age" : 38,
  "position" : [ "Founder", "CTO", "Writer" ]
}

8.2 @JsonIgnoreProperties to ignore fields on class level.


import com.fasterxml.jackson.annotation.JsonIgnoreProperties;

@JsonIgnoreProperties({"salary", "position"})
public class Staff {

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

Output


{
  "name" : "mkyong",
  "age" : 38,
  "skills" : [ "java", "python", "node", "kotlin" ]
}

9. FAQs

9.1 Convert JSON array string to List


	String json = "[{\"name\":\"mkyong\", \"age\":38}, {\"name\":\"laplap\", \"age\":5}]";

	List<Staff> list = Arrays.asList(mapper.readValue(json, Staff[].class));
	
	// or like this:
	// List<Staff> list = mapper.readValue(json, new TypeReference<List<Staff>>(){});

9.2 Convert JSON string to Map


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

	map.forEach((k, v) -> System.out.format("[key]:%s \t[value]:%s\n", k, v));

Output


[key]:name 	[value]:mkyong
[key]:age 	[value]:33

9.3 What if some complex JSON structure doesn’t map easily to a Java class?
Answer: Try Jackson TreeModel to convert JSON data into JsonNode, so that we can add, update or delete JSON nodes easily.

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