Java Jackson Library
Jackson is a high-performance JSON processing library for Java, which can:
- Serialize Java objects to JSON format (Object → JSON)
- Deserialize JSON to Java objects (JSON → Object)
Jackson has become one of the most popular JSON processing libraries in the Java ecosystem due to its speed, power, and ease of use.
Jackson Core Modules
- 1. Jackson Core: The core module of Jackson, providing basic JSON parsing and generation capabilities.
- 2. Jackson Annotations: Contains various annotations used to control the serialization and deserialization process.
- 3. Jackson Databind: Provides data binding functionality, enabling conversion between Java objects and JSON.
Basic Usage
Add Dependency
First, you need to add the Jackson dependency to your project (using Maven as an example):<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
A simple example of converting between Java and JSON objects:
Example
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 ObjectMapper
ObjectMapperIs Jackson's core class, responsible for serialization and deserialization:
ObjectMapper mapper = new ObjectMapper();
JSON Serialization (Object → JSON)
Simple Example
Example
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
.writeValueAsString(person);
System.out.println(prettyJson);
/*
Output:
{
"name" : "Zhang San",
"age" : 25
}
*/
JSON Deserialization (JSON → Object)
Simple Example
Example
Person person = mapper.readValue(json, Person.class);
System.out.println(person.getName()); // Output: Li Si
Reading from 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
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 Type
Example
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 inheritingJsonSerializerandJsonDeserializerCustom serialization and deserialization logic can be implemented.
Polymorphic Type Handling
Use@JsonTypeInfoand@JsonSubTypesAnnotations to handle inheritance and polymorphism.
Tree Model
Jackson provides a Tree Model API that allows direct manipulation of JSON nodes:
Example
String name = rootNode.get("name").asText();
int age = rootNode.get("age").asInt();
Best Practices
- Reuse ObjectMapper: Creating
ObjectMapperInstances are expensive to create; the same instance should be reused - Handle Exceptions: Always handle
JsonProcessingExceptionandIOException - Use DTO Pattern: Don't directly serialize domain models; use dedicated Data Transfer Objects (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 capability
- Rich customization options
- Good community support
Mastering Jackson can greatly improve the efficiency and flexibility of handling JSON data in Java development.
Other Extensions
Java Common Libraries