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' : 'favtuts'}", 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.favtuts.json; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import com.favtuts.json.pojo.Staff; public class JacksonParseJSON { public static void main(String[] args) { javaObjectsToJSON(); } static void javaObjectsToJSON() { ObjectMapper mapper = new ObjectMapper(); Staff staff = createStaff(); try { // Java objects to JSON file mapper.writeValue(new File("/home/tvt/workspace/favtuts/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("favtuts"); 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
/home/tvt/workspace/favtuts/staff.json
{"name":"favtuts","age":38,"position":["Founder","CTO","Writer"],"skills":["java","python","node","kotlin"],"salary":{"2018":14000,"2012":12000,"2010":10000}}
Terminal
{"name":"favtuts","age":38,"position":["Founder","CTO","Writer"],"skills":["java","python","node","kotlin"],"salary":{"2018":14000,"2012":12000,"2010":10000}}
{
"name" : "favtuts",
"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.favtuts.json; import com.fasterxml.jackson.databind.ObjectMapper; import java.io.File; import java.io.IOException; import com.favtuts.json.pojo.Staff; public class JacksonParseJSON { public static void main(String[] args) { jsonToJavaObject(); } static void jsonToJavaObject() { ObjectMapper mapper = new ObjectMapper(); try { // JSON file to Java object Staff staff = mapper.readValue(new File("/home/tvt/workspace/favtuts/staff.json"), Staff.class); // JSON string to Java object String jsonInString = "{\"name\":\"favtuts\",\"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='favtuts', age='37', position='null', skills='[java, python]', salary='null'}
{
"name" : "favtuts",
"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" : "favtuts",
"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" : "favtuts",
"age" : 38,
"skill" : null,
"salary" : null
}
6.3 Globally.
ObjectMapper mapper = new ObjectMapper(); // ignore all null fields globally mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
Note
More examples for How to ignore null fields with Jackson
7. @JsonView
7.1 The @JsonView
is used to limit fields display for different users. For example:
CompanyViews.java
package com.favtuts.json; 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.favtuts.json; import java.io.IOException; import java.math.BigDecimal; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.favtuts.json.pojo.Staff; public class JacksonParseJSON { public static void main(String[] args) { testJsonViewMapper(); } static void testJsonViewMapper() { 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("favtuts"); 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" : "favtuts",
"age" : 38
}
Manager views
{
"name" : "favtuts",
"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" : "favtuts",
"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" : "favtuts",
"age" : 38,
"skills" : [ "java", "python", "node", "kotlin" ]
}
9. FAQs
9.1 Convert JSON array string to List
String json = "[{\"name\":\"favtuts\", \"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\":\"favtuts\", \"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]:favtuts
[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.
Download Source Code
$ git clone https://github.com/favtuts/java-core-tutorials-examples
$ cd java-basic/json