Java Jackson Library
Jackson is a high-performance JSON processing library for Java that can:
- Serialize Java objects into JSON format (object → JSON)
- Deserialize JSON into Java objects (JSON → object)
Jackson has become one of the most popular JSON processing libraries in the Java ecosystem because of its speed, powerful features, and ease of use.
Jackson Core Modules
-
- Jackson Core: The core module of Jackson, providing basic JSON parsing and generation capabilities.
-
- Jackson Annotations: Contains various annotations used to control the serialization and deserialization process.
-
- Jackson Databind: Provides data binding functionality, enabling conversion between Java objects and JSON.
Basic Usage
Add Dependency
First, add the Jackson dependency to your project (using Maven as an example):
com.fasterxml.jackson.core
jackson-databind
2.13.0
A simple example that converts between Java and JSON objects:
Example
import
com.fasterxml.jackson.databind.ObjectMapper
;
public
class
JacksonDemo
{
public
static
void
main
(
String
[
]
args
)
throws
Exception
{
ObjectMapper mapper
=
new
ObjectMapper
(
)
;
// Java object to JSON
Person person
=
new
Person
(
"Zhang San"
,
30
)
;
String
json
=
mapper.
writeValueAsString
(
person
)
;
System
.
out
.
println
(
json
)
;
// JSON to Java object
Person parsedPerson
=
mapper.
readValue
(
json, Person.
class
)
;
System
.
out
.
println
(
parsedPerson
)
;
}
}
class
Person
{
private
String
name
;
private
int
age
;
// Must have a no-argument constructor
public
Person
(
)
{
}
public
Person
(
String
name,
int
age
)
{
this
.
name
=
name
;
this
.
age
=
age
;
}
// Must have getters and setters
// Omit getters/setters and toString method
}
Creating an ObjectMapper
ObjectMapper is the core class of Jackson, responsible for serialization and deserialization:
ObjectMapper mapper = new ObjectMapper();
JSON Serialization (object → JSON)
Simple Example
Example
public
class
Person
{
private
String
name
;
private
int
age
;
// Omit constructor, getters and setters
}
Person person
=
new
Person
(
"Zhang San"
,
25
)
;
String
json
=
mapper.
writeValueAsString
(
person
)
;
System
.
out
.
println
(
json
)
;
// Output: {"name":"Zhang San","age":25}
Formatted output
Example
String
prettyJson
=
mapper.
writerWithDefaultPrettyPrinter
(
)
.
writeValueAsString
(
person
)
;
System
.
out
.
println
(
prettyJson
)
;
/*
Output:
{
"name" : "Zhang San",
"age" : 25
}
*/
JSON Deserialization (JSON → object)
Simple Example
Example
String
json
=
"{"name":"Li Si","age":30}"
;
Person person
=
mapper.
readValue
(
json, Person.
class
)
;
System
.
out
.
println
(
person.
getName
(
)
)
;
// Output: Li Si
Reading from a File
Person person = mapper.readValue(new File("person.json"), Person.class);
Common Annotations
Jackson provides various annotations to control the serialization and deserialization process:
@JsonProperty
Specify the JSON property name:
@JsonProperty("user_name")
private String name;
@JsonIgnore
Ignore a certain field:
@JsonIgnore
private String password;
@JsonFormat
Format dates:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd")
private Date birthDate;
Handling Complex Types
Collection Types
Example
List
people
=
Arrays
.
asList
(
new
Person
(
"Wang Wu"
,
28
)
,
new
Person
(
"Zhao Liu"
,
32
)
)
;
String
json
=
mapper.
writeValueAsString
(
people
)
;
// Output: [{"name":"Wang Wu","age":28},{"name":"Zhao Liu","age":32}]
Map Types
Example
Map
<
String
, Object
data
=
new
HashMap
<>
(
)
;
data.
put
(
"name"
,
"Zhang San"
)
;
data.
put
(
"age"
,
25
)
;
data.
put
(
"isStudent"
,
true
)
;
String
json
=
mapper.
writeValueAsString
(
data
)
;
// Output: {"name":"Zhang San","age":25,"isStudent":true}
Advanced Features
Custom Serialization/Deserialization
By extending JsonSerializer and JsonDeserializer you can implement custom serialization and deserialization logic.
Polymorphic Type Handling
Use @JsonTypeInfo and @JsonSubTypes Annotations handle inheritance and polymorphism.
Tree Model
Jackson provides a tree model API that can directly manipulate JSON nodes:
Example
JsonNode rootNode
=
mapper.
readTree
(
json
)
;
String
name
=
rootNode.
get
(
"name"
)
.
asText
(
)
;
int
age
=
rootNode.
get
(
"age"
)
.
asInt
(
)
;
Best Practices
- Reuse the ObjectMapper: Creating
ObjectMapperinstances is expensive, so the same instance should be reused - Handle Exceptions: Always handle
JsonProcessingExceptionandIOException - Use the DTO Pattern: Do not serialize the domain model directly; use a dedicated Data Transfer Object (DTO)
- Consider Performance: For high-performance scenarios, you can use
JsonFactoryfor low-level operations
Summary
Jackson is a powerful tool for handling JSON in Java, providing:
- Simple and easy-to-use API
- High-performance JSON processing capabilities
- Rich customization options
- Good community support
Mastering Jackson can greatly improve the efficiency and flexibility of processing JSON data in Java development.
Common Java Libraries