Jackson Quick Guide
Jackson Quick Guide
JACKSON - OVERVIEW
Jackson is a simple Java-based library to serialize Java objects to JSON and vice versa.
Features of Jackson
Easy to use − Jackson API provides a high-level facade to simplify commonly used use-
cases.
No need to create mapping − Jackson API provides default mapping for most of the
objects to be serialized.
Performance − Jackson is quite fast, consumes less memory space, and is suitable for large
object graphs or systems.
Clean JSON − Jackson creates clean and compact JSON results which are easy to read.
No Dependency − Jackson library does not require any other library apart from JDK.
Streaming API − It reads and writes JSON content as discrete events. JsonParser reads the
data, whereas JsonGenerator writes the data.
It has the lowest overhead and it provides the fastest way to perform read/write
operations.
Data Binding − It converts JSON to and from Plain Old Java Object (POJO) using property
accessor or using annotations. ObjectMapper reads/writes JSON for both types of data
bindings. Data binding is analogous to JAXB parser for XML. Data binding is of two types −
Simple Data Binding − It converts JSON to and from Java Maps, Lists, Strings,
Numbers, Booleans, and null objects.
Full Data Binding − It converts JSON to and from any Java type.
This chapter describes how to set up the Jackson environment on your system.
For most of the examples given in this tutorial, you will find a Try it option to help you
learn quickly through practice.
Java SE is freely available from the link Download Java. You can download a version based on your
operating system.
Follow the instructions to download Java and run the .exe to install Java on your machine. Once
you have installed Java, you would need to set the environment variables to point to the correct
installation directories.
Select 'Properties'.
Alter the 'Path' variable so that it also contains the path to the Java executable. For example,
if the path is currently set to 'C:\WINDOWS\SYSTEM32', then change your path to read
'C:\WINDOWS\SYSTEM32;c:\Program Files\java\jdk\bin'.
For example, if you use bash as your shell, then you need to add the following line at the end of
your '.bashrc: export PATH=/path/to/java:$PATH'.
Notepad − On Windows platform, you can use any simple text editor such as Notepad
(recommended for this tutorial) or TextPad.
Netbeans − It is an open-source Java IDE. It can be downloaded from
http://www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the Eclipse open-source community. It can be
downloaded from http://www.eclipse.org/.
OS Archive name
Windows jackson-all-1.9.0.jar
Linux jackson-all-1.9.0.jar
Mac jackson-all-1.9.0.jar
OS Output
OS Output
Jackson Example
In the following example, we will create a Student class. Thereafter, we will create a JSON string
with Student details and deserialize it to Student object and then serialize it back to a JSON string.
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
try {
Student student = mapper.readValue(jsonString, Student.class);
System.out.println(student);
mapper.enable(SerializationConfig.Feature.INDENT_OUTPUT);
jsonString = mapper.writeValueAsString(student);
System.out.println(jsonString);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
Verifythe Result
Compile the classes using javac compiler as follows −
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
Verify the Output −
Steps to Remember
Following are the important steps to be considered here.
Customized TypeResolverBuilder that provides type resolver builders used with so-
called "default typing" (see enableDefaultTyping() for details).
1 ObjectMapper()
It is the default constructor, which constructs the default JsonFactory as necessary. Use
StdSerializerProvider as its SerializerProvider, and BeanSerializerFactory as its
SerializerFactory.
2 ObjectMapper(JsonFactory jf)
5 ObjectMapper(SerializerFactory sf)
Deprecated. Use other constructors instead; note that you can set the serializer factory
with setSerializerFactory(org.codehaus.jackson.map.SerializerFactory)
ObjectMapper Methods
Method called to configure the generator as necessary and then call write functionality.
Helper method that should return default pretty-printer to use for generators
constructed by this mapper, when instructed to use default pretty printer.
6 protected JsonDeserializer<Object>
_findRootDeserializer(DeserializationConfig cfg, JavaType valueType)
Method called to ensure that given parser is ready for reading content for data binding.
8 protected Object _readMapAndClose(JsonParser jp, JavaType valueType)
Method that can be called to check whether mapper thinks it could deserialize an Object
of given type.
Method that can be called to check whether mapper thinks it could serialize an instance
of given Class.
Method for changing state of an on/off deserialization feature for this object mapper.
Method for changing state of an on/off JsonGenerator feature for JsonFactory instance
this object mapper uses.
Method for changing state of an on/off JsonParser feature for JsonFactory instance this
object mapper uses.
Method for changing state of an on/off serialization feature for this object mapper.
17 JavaType constructType(Type t)
Convenience method for doing two-step conversion from given value, into instance of
given value type.
21 DeserializationConfig copyDeserializationConfig()
Method that creates a copy of the shared default DeserializationConfig object that
defines configuration settings for deserialization.
22 SerializationConfig copySerializationConfig()
Method that creates a copy of the shared default SerializationConfig object that defines
configuration settings for serialization.
23 ArrayNode createArrayNode()
24 ObjectNode createObjectNode()
25 ObjectWriter defaultPrettyPrintingWriter()
26 ObjectMapper disable(DeserializationConfig.Feature... f)
27 ObjectMapper disable(SerializationConfig.Feature... f)
28 ObjectMapper disableDefaultTyping()
Method for disabling automatic inclusion of type information; if so, only explicitly
annotated types (ones with JsonTypeInfo) has additional embedded type information.
29 ObjectMapper enable(DeserializationConfig.Feature... f)
30 ObjectMapper enable(SerializationConfig.Feature... f)
31 ObjectMapper enableDefaultTyping()
Method for enabling automatic inclusion of type information, needed for proper
deserialization of polymorphic types (unless types are annotated with JsonTypeInfo).
34 ObjectMapper enableDefaultTypingAsProperty(ObjectMapper.DefaultTyping
applicability, String propertyName)
Method for enabling automatic inclusion of type information -- needed for proper
deserialization of polymorphic types (unless types have been annotated with
JsonTypeInfo) -- using "As.PROPERTY" inclusion mechanism and specified property
name to use for inclusion (default being "@class" since default type information always
uses class name as type identifier)
36 JsonSchema generateJsonSchema(Class<?> t)
38 DeserializationConfig getDeserializationConfig()
Method that returns the shared default DeserializationConfig object that defines
configuration settings for deserialization.
39 DeserializerProvider getDeserializerProvider()
40 JsonFactory getJsonFactory()
Method that can be used to get hold of JsonFactory that this mapper uses if it needs to
construct JsonParsers and/or JsonGenerators.
41 JsonNodeFactory getNodeFactory()
Method that can be used to get hold of JsonNodeFactory that this mapper will use when
directly constructing root JsonNode instances for Trees.
42 SerializationConfig getSerializationConfig()
Method that returns the shared default SerializationConfig object that defines
configuration settings for serialization.
43 SerializerProvider getSerializerProvider()
44 SubtypeResolver getSubtypeResolver()
45 TypeFactory getTypeFactory()
46 VisibilityChecker<?> getVisibilityChecker()
Method for accessing currently configured visibility checker; object used for
determining whether given property element (method, field, constructor) can be auto-
detected or not.
47 boolean isEnabled(DeserializationConfig.Feature f)
48 boolean isEnabled(JsonGenerator.Feature f)
49 boolean isEnabled(JsonParser.Feature f)
50 boolean isEnabled(SerializationConfig.Feature f)
52 ObjectReader reader()
Factory method for constructing ObjectReader that will pass specific schema object to
JsonParser used for reading content.
Factory method for constructing ObjectReader that will use specified injectable values.
Factory method for constructing ObjectReader that will read or update instances of
specified type.
57 ObjectReader reader(JsonNodeFactory f)
Factory method for constructing ObjectReader that will use specified JsonNodeFactory
for constructing JSON trees.
Factory method for constructing ObjectReader that will read or update instances of
specified type.
Factory method for constructing ObjectReader that will update given Object (usually
Bean, but can be a Collection or Map as well, but NOT an array) with JSON data.
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
63 JsonNode readTree(JsonParser jp)
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
65 JsonNode readTree(Reader r)
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
Method to deserialize JSON content as tree expressed using set of JsonNode instances.
Convenience method for converting results from given JSON tree into given value type.
Convenience method for converting results from given JSON tree into given value type.
Convenience method for converting results from given JSON tree into given value type.
Method to deserialize JSON content into a non-container type (it can be an array type,
however) − typically a bean, array or a wrapper type (like Boolean).
84 <T> T readValue(JsonParser jp, Class<T> valueType, DeserializationConfig cfg)
Method to deserialize JSON content into a non-container type (it can be an array type,
however) − typically a bean, array or a wrapper type (like Boolean).
Method to deserialize JSON content into a Java type, reference to which is passed as
argument.
Method to deserialize JSON content into a Java type, reference to which is passed as
argument.
Method to deserialize JSON content into a Java type, reference to which is passed as
argument.
Method to deserialize JSON content into a Java type, reference to which is passed as
argument.
Method for registering a module that can extend functionality provided by this mapper;
for example, by adding providers for custom serializers and deserializers.
102 void registerSubtypes(Class<?>... classes)
Method for changing AnnotationIntrospector used by this mapper instance for both
serialization and deserialization.
Method for configuring the default DateFormat to use when serializing time values as
Strings, and deserializing from JSON Strings.
Method for enabling automatic inclusion of type information, using specified handler
object for determining which types this affects, as well as details of how information is
embedded.
Method for setting specific DeserializerProvider to use for handling the caching of
JsonDeserializer instances.
Method for specifying JsonNodeFactory to use for constructing root level tree nodes (via
method createObjectNode()
Method for setting default POJO property inclusion strategy for serialization.
Method for setting specific SerializerFactory to use for constructing (bean) serializers.
Method that can be used to override TypeFactory instance used by this mapper.
Method for setting currently configured visibility checker; object used to determine
whether given property element (method, field, constructor) can be auto-detected or
not.
Convenience conversion method that binds data provided the JSON tree contains a
specific value (usually bean) type.
Method that will return version information stored and reads from jar that contains this
class.
Factory method for constructing ObjectWriter that serializes objects using specified
DateFormat; or, if null passed, using timestamp (64-bit number.
Factory method for constructing ObjectWriter that serializes objects using specified
filter provider.
Factory method for constructing ObjectWriter that passes specific schema object to
JsonGenerator used for writing content.
Factory method for constructing ObjectWriter that serializes objects using specified
pretty printer for indentation (or if null, no pretty printer)
Factory method for constructing ObjectWriter that serializes objects using the default
pretty printer for indentation.
Factory method for constructing ObjectWriter that serializes objects using specified root
type, instead of actual runtime type of value.
Factory method for constructing ObjectWriter that serializes objects using specified root
type, instead of actual runtime type of value.
Factory method for constructing ObjectWriter that serializes objects using specified root
type, instead of actual runtime type of value.
Factory method for constructing ObjectWriter that serializes objects using specified
JSON View (filter).
Method that can be used to serialize any Java value as JSON output, written to File
provided.
Method that can be used to serialize any Java value as JSON output, using provided
JsonGenerator.
Method that can be used to serialize any Java value as JSON output, using provided
JsonGenerator, configured as per passed configuration object.
Method that can be used to serialize any Java value as JSON output, using output stream
provided (using encoding JsonEncoding.UTF8).
Method that can be used to serialize any Java value as JSON output, using Writer
provided.
File: JacksonTester.java
import java.io.IOException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.SerializationConfig;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
C:\Jackson_WORKSPACE>java JacksonTester
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
try {
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
tester.writeJSON(student);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class Student {
private String name;
private int age;
public Student(){}
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
Simple Data Binding − It converts JSON to and from Java Maps, Lists, Strings, Numbers,
Booleans, and null objects.
Full Data Binding − It converts JSON to and from any Java type.
ObjectMapper reads/writes JSON for both types of data bindings. Data binding is analogous to JAXB
parser for XML.
We will cover simple data binding in this chapter. Full data binding is discussed separately in the
next chapter.
2 array ArrayList<Object>
3 string String
7 null null
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
try {
ObjectMapper mapper = new ObjectMapper();
student.setAge(10);
student.setName("Mahesh");
// JAVA Object
studentDataMap.put("student", student);
// JAVA String
studentDataMap.put("name", "Mahesh Kumar");
// JAVA Boolean
studentDataMap.put("verified", Boolean.FALSE);
// Array
studentDataMap.put("marks", marks);
mapper.writeValue(new File("student.json"), studentDataMap);
//result student.json
//{
// "student":{"name":"Mahesh","age":10},
// "marks":[1,2,3],
// "verified":false,
// "name":"Mahesh Kumar"
//}
System.out.println(studentDataMap.get("student"));
System.out.println(studentDataMap.get("name"));
System.out.println(studentDataMap.get("verified"));
System.out.println(studentDataMap.get("marks"));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
{name=Mahesh, age=10}
Mahesh Kumar
false
[1, 2, 3]
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
try {
Student student = new Student();
student.setAge(10);
student.setName("Mahesh");
tester.writeJSON(student);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
class Student {
private String name;
private int age;
public Student(){}
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
Consider the following example with a class UserData, a class to hold user-specific data.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
// JAVA Object
studentData.setStudent(student);
// JAVA String
studentData.setName("Mahesh Kumar");
// JAVA Boolean
studentData.setVerified(Boolean.FALSE);
// Array
studentData.setMarks(marks);
TypeReference ref = new TypeReference<Map<String,UserData>>() { };
userDataMap.put("studentData1", studentData);
mapper.writeValue(new File("student.json"), userDataMap);
//{
// "studentData1":
// {
// "student":
// {
// "name":"Mahesh",
// "age":10
// },
// "name":"Mahesh Kumar",
// "verified":false,
// "marks":[1,2,3]
// }
//}
userDataMap = mapper.readValue(new File("student.json"), ref);
System.out.println(userDataMap.get("studentData1").getStudent());
System.out.println(userDataMap.get("studentData1").getName());
System.out.println(userDataMap.get("studentData1").getVerified());
System.out.println(Arrays.toString(userDataMap.get("studentData1").getMarks()));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
private String name;
private int age;
public Student(){}
class UserData {
private Student student;
private String name;
private Boolean verified;
private int[] marks;
public UserData(){}
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run the jacksonTester to see the result −
C:\Jackson_WORKSPACE>java JacksonTester
Traversing a Tree
Get each node using the relative path to the root node while traversing the tree and process the
data. The following code snippet shows how to traverse a tree, provided you have information
regarding the root node.
File: JacksonTester.java
import java.io.IOException;
import java.util.Iterator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.getIntValue() + " ");
}
System.out.println("]");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
while (iterator.hasNext()) {
JsonNode marks = iterator.next();
System.out.print(marks.getIntValue() + " ");
}
System.out.println("]");
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.node.ArrayNode;
import org.codehaus.jackson.node.ObjectNode;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
class Student {
String name;
int age;
boolean verified;
int[] marks;
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
It is the most powerful approach among the three processing modes that Jackson supports.
It has the lowest overhead and it provides the fastest way to perform read/write operations.
// {
jsonGenerator.writeStartObject();
// "name" : "Mahesh Kumar"
Let us see JsonGenerator in action. Create a Java class file named JacksonTester in
C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import java.util.Map;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
try {
JsonFactory jasonFactory = new JsonFactory();
// {
jsonGenerator.writeStartObject();
// "age" : 21
jsonGenerator.writeNumberField("age", 21);
// "verified" : false
jsonGenerator.writeBooleanField("verified", false);
// [
jsonGenerator.writeStartArray();
// 100, 90, 85
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
// ]
jsonGenerator.writeEndArray();
// }
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
System.out.println(dataMap.get("name"));
System.out.println(dataMap.get("age"));
System.out.println(dataMap.get("verified"));
System.out.println(dataMap.get("marks"));
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
Mahesh Kumar
21
false
[100, 90, 85]
if ("name".equals(fieldname)) {
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getText());
}
}
Let us see JsonParser in action. Create a Java class file named JacksonTester in
C:\>Jackson_WORKSPACE.
File: JacksonTester.java
import java.io.File;
import java.io.IOException;
import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.JsonToken;
import org.codehaus.jackson.map.JsonMappingException;
jsonGenerator.writeBooleanField("verified", false);
jsonGenerator.writeFieldName("marks");
jsonGenerator.writeStartArray(); // [
jsonGenerator.writeNumber(100);
jsonGenerator.writeNumber(90);
jsonGenerator.writeNumber(85);
jsonGenerator.writeEndArray();
jsonGenerator.writeEndObject();
jsonGenerator.close();
//result student.json
//{
// "name":"Mahesh Kumar",
// "age":21,
// "verified":false,
// "marks":[100,90,85]
//}
if("age".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getNumberValue());
}
if("verified".equals(fieldname)){
//move to next token
jsonParser.nextToken();
System.out.println(jsonParser.getBooleanValue());
}
if("marks".equals(fieldname)){
//move to [
jsonParser.nextToken();
// loop till token equal to "]"
C:\Jackson_WORKSPACE>javac JacksonTester.java
C:\Jackson_WORKSPACE>java JacksonTester
Mahesh Kumar
21
false
[100, 90, 85]