Jackson使用手册
Jackson是Java生态中最流行的JSON处理库之一,主要用于:
- 将Java对象序列化为JSON字符串
- 将JSON字符串反序列化为Java对象
- 将JSON字符串转为List集合
- 将List集合转为JSON字符串
- 将JSON字符串转为Map
- 将Map转为JSON字符串
- 将JSON字符串转为数组
- 将数组转为JSON字符串
- 处理JSON数据的各种操作
1. Jackson简介
Jackson核心模块:
jackson-core
- 核心包,定义流式APIjackson-annotations
- 注解包jackson-databind
- 数据绑定包
2. 基本依赖配置
Maven依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
Gradle依赖
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'
3. 核心API
3.1 ObjectMapper
ObjectMapper
是Jackson最核心的类,用于对象与JSON之间的转换。
ObjectMapper mapper = new ObjectMapper();
3.2 常用配置
// 常用配置
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); // 忽略未知属性
mapper.enable(SerializationFeature.INDENT_OUTPUT); // 美化输出
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 日期不序列化为时间戳
4. 基本操作
4.1 Java对象转JSON
import com.fasterxml.jackson.databind.ObjectMapper;
public class JavaObjectToJsonExample {
public static void main(String[] args) throws Exception {
User user = new User("张三", 25);
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
// 输出: {"name":"张三","age":25}
}
}
4.2 JSON转Java对象
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToJavaObjectExample {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"张三\",\"age\":25}";
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
}
}
4.3 JSON 字符串转为 List集合
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class JsonToListExample {
public static void main(String[] args) throws Exception {
String jsonStr = "[{\"name\":\"A\",\"age\":20}, {\"name\":\"B\",\"age\":25}]";
ObjectMapper mapper = new ObjectMapper();
// 反序列化
List<User> users = mapper.readValue(jsonStr, new TypeReference<List<User>>() {});
for (User user : users) {
System.out.println(user);
}
}
}
4.4 List集合转为JSON字符串
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.List;
public class ListToJsonExample {
public static void main(String[] args) throws Exception {
List<User> users = Arrays.asList(
new User("张三", 25),
new User("李四", 30)
);
ObjectMapper mapper = new ObjectMapper();
// 序列化
String jsonStr = mapper.writeValueAsString(users);
}
}
4.5 JSON 字符串转为 Map<String, Object>
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;
public class JsonToMapExample {
public static void main(String[] args) throws Exception {
String jsonStr = "{\"name\":\"Tom\",\"age\":25}";
ObjectMapper mapper = new ObjectMapper();
Map<String, Object> map = mapper.readValue(jsonStr, Map.class);
System.out.println("Name: " + map.get("name"));
System.out.println("Age: " + map.get("age"));
}
}
4.6 Map<String, Object>转为 JSON 字符串
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;
public class MapToJsonExample {
public static void main(String[] args) throws Exception {
// 创建一个 Map
Map<String, Object> map = new HashMap<>();
map.put("name", "Tom");
map.put("age", 25);
map.put("isStudent", false);
map.put("hobbies", new String[]{"reading", "sports"});
// 使用 Jackson 转换为 JSON 字符串
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writeValueAsString(map);
System.out.println(jsonString);
// 输出: {"name":"Tom","age":25,"isStudent":false,"hobbies":["reading","sports"]}
}
}
4.7 JSON 字符串转为数组
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonToArrayExample {
public static void main(String[] args) throws Exception {
String jsonStr = "[{\"name\":\"X\",\"age\":30}, {\"name\":\"Y\",\"age\":35}]";
ObjectMapper mapper = new ObjectMapper();
User[] userArray = mapper.readValue(jsonStr, User[].class);
for (User user : userArray) {
System.out.println(user);
}
}
}
4.8 数组转为JSON 字符串
import com.fasterxml.jackson.databind.ObjectMapper;
public class ArrayToJsonExample {
public static void main(String[] args) throws Exception {
User[] users = {
new User("Tom", 25),
new User("Jerry", 30)
};
ObjectMapper mapper = new ObjectMapper();
String jsonStr = mapper.writeValueAsString(users);
System.out.println(jsonStr);
// 输出: [{"name":"Tom","age":25},{"name":"Jerry","age":30}]
}
}
5. 高级特性
5.1 注解使用
@JsonProperty
指定JSON属性名
public class User {
@JsonProperty("user_name")
private String name;
@JsonProperty("user_age")
private int age;
}
@JsonIgnore
忽略属性
public class User {
private String name;
@JsonIgnore
private String password;
}
@JsonFormat
格式化日期
public class Event {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private Date eventDate;
}
5.2 自定义序列化/反序列化
自定义序列化器
public class CustomSerializer extends StdSerializer<User> {
public CustomSerializer() {
super(User.class);
}
@Override
public void serialize(User value, JsonGenerator gen, SerializerProvider provider) {
gen.writeStartObject();
gen.writeStringField("username", value.getName());
gen.writeNumberField("years", value.getAge());
gen.writeEndObject();
}
}
// 使用
SimpleModule module = new SimpleModule();
module.addSerializer(User.class, new CustomSerializer());
mapper.registerModule(module);
自定义反序列化器
public class CustomDeserializer extends StdDeserializer<User> {
public CustomDeserializer() {
super(User.class);
}
@Override
public User deserialize(JsonParser p, DeserializationContext ctxt) {
// 实现反序列化逻辑
}
}
6. 处理复杂场景
6.1 多态类型处理
@JsonTypeInfo(
use = JsonTypeInfo.Id.NAME,
include = JsonTypeInfo.As.PROPERTY,
property = "type"
)
@JsonSubTypes({
@JsonSubTypes.Type(value = Dog.class, name = "dog"),
@JsonSubTypes.Type(value = Cat.class, name = "cat")
})
public abstract class Animal {
private String name;
}
public class Dog extends Animal {
private double barkVolume;
}
public class Cat extends Animal {
private boolean likesCream;
}
6.2 处理树模型
String json = "{\"name\":\"张三\",\"age\":25}";
JsonNode node = mapper.readTree(json);
String name = node.get("name").asText();
int age = node.get("age").asInt();
7. 性能优化
7.1 重用ObjectMapper
ObjectMapper
是线程安全的,应该重用而不是每次创建新实例。
7.2 使用JsonFactory
JsonFactory factory = mapper.getFactory();
7.3 使用流式API处理大JSON
JsonFactory factory = new JsonFactory();
JsonParser parser = factory.createParser(new File("large.json"));
while (parser.nextToken() != null) {
// 处理每个token
}
parser.close();
8. 常见问题解决
8.1 处理循环引用
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
public class User {
private int id;
private String name;
private List<User> friends;
}
8.2 处理空值
mapper.setSerializationInclusion(Include.NON_NULL); // 忽略null值
9. 最佳实践
- 始终重用
ObjectMapper
实例 - 为复杂对象使用注解简化处理
- 处理大文件时使用流式API
- 合理配置序列化和反序列化特性
- 使用
TypeReference
处理泛型集合
10. 扩展阅读
本手册涵盖了Jackson的核心功能和常见用法,可作为日常开发的参考指南。根据实际需求,可以进一步探索Jackson更高级的特性。