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://bit.ly/1WH8gE6"), 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
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. Jackson 2 Dependency
2.1 For Jackson 2.x, declares jackson-databind
, it will download its dependencies – jackson-core
and jackson-annotations
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.6.3</version>
</dependency>
2.2 Review the Jackson dependencies :
[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.
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.
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.
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).
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.
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 :
- mapper.writerWithView(“view class”).writeValue()
- mapper.readerWithView(“view class”).readValue()
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]]
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>>(){});
View more at: http://bit.ly/1XReQFr
Post a Comment