Jackson 是 Java 生態中最流行的 JSON 處理庫,也是 Spring Boot 的默認 JSON 解析器。它提供了高性能的 JSON 序列化(對象 → JSON)和反序列化(JSON → 對象)功能。以下是 Jackson 的全面使用指南。
1. 基礎依賴
Maven 依賴
<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.15.0</version> <!-- 使用最新版本 -->
</dependency>
Spring Boot 項目無需手動引入,默認已集成。
2. 核心類:ObjectMapper
ObjectMapper
是 Jackson 的核心類,負責序列化和反序列化操作。
import com.fasterxml.jackson.databind.ObjectMapper;ObjectMapper mapper = new ObjectMapper();
3. 基礎用法
3.1 序列化(對象 → JSON)
Person person = new Person("Alice", 30);
String json = mapper.writeValueAsString(person);
// 輸出: {"name":"Alice","age":30}
3.2 反序列化(JSON → 對象)
String json = "{\"name\":\"Alice\",\"age\":30}";
Person person = mapper.readValue(json, Person.class);
System.out.println(person.getName()); // 輸出: Alice
3.3 序列化到文件/從文件反序列化
// 寫入文件
mapper.writeValue(new File("person.json"), person);// 從文件讀取
Person person = mapper.readValue(new File("person.json"), Person.class);
4. 常用注解
Jackson 提供注解來控制序列化/反序列化行為。
4.1 字段控制
注解 | 作用 | 示例 |
---|---|---|
@JsonProperty | 自定義 JSON 字段名 | @JsonProperty("user_name") |
@JsonIgnore | 忽略字段 | @JsonIgnore private String password |
@JsonInclude | 僅包含非空字段 | @JsonInclude(Include.NON_NULL) |
4.2 日期格式化
public class Event {@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")private Date createTime;
}
4.3 忽略未知字段
@JsonIgnoreProperties(ignoreUnknown = true)
public class Person {private String name;
}
5. 復雜對象處理
5.1 嵌套對象
public class Order {private String orderId;private Person customer; // 嵌套對象
}String json = "{\"orderId\":\"123\",\"customer\":{\"name\":\"Alice\"}}";
Order order = mapper.readValue(json, Order.class);
5.2 集合類型
// List 序列化/反序列化
List<Person> people = Arrays.asList(new Person("Alice"), new Person("Bob"));
String json = mapper.writeValueAsString(people);List<Person> parsedList = mapper.readValue(json, new TypeReference<List<Person>>() {});
5.3 Map 類型
Map<String, Person> personMap = new HashMap<>();
personMap.put("alice", new Person("Alice"));String json = mapper.writeValueAsString(personMap);
Map<String, Person> parsedMap = mapper.readValue(json, new TypeReference<Map<String, Person>>() {});
6. 高級配置
6.1 美化輸出(Pretty Print)
String prettyJson = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(person);
6.2 自定義序列化/反序列化
// 自定義序列化器
public class CustomSerializer extends JsonSerializer<Person> {@Overridepublic void serialize(Person value, JsonGenerator gen, SerializerProvider provider) {gen.writeString(value.getName().toUpperCase());}
}// 注冊自定義序列化器
SimpleModule module = new SimpleModule();
module.addSerializer(Person.class, new CustomSerializer());
mapper.registerModule(module);
7. 與 Spring Boot 集成
Spring Boot 自動配置了 ObjectMapper
,可通過以下方式自定義:
7.1 全局配置
@Configuration
public class JacksonConfig {@Beanpublic ObjectMapper objectMapper() {ObjectMapper mapper = new ObjectMapper();mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);return mapper;}
}
7.2 REST 控制器示例
@RestController
public class PersonController {@GetMapping("/person")public Person getPerson() {return new Person("Alice", 30); // 自動轉為JSON}@PostMapping("/person")public Person createPerson(@RequestBody Person person) { // 自動從JSON反序列化return person;}
}
8. 性能優化建議
-
重用
ObjectMapper
避免重復創建,推薦作為單例使用。 -
使用
TypeReference
處理泛型List<Person> people = mapper.readValue(json, new TypeReference<List<Person>>() {});
-
啟用緩存
mapper.enable(SerializationFeature.USE_EQUALITY_FOR_OBJECT_ID);
9. 常見問題
Q1: 如何處理循環引用?
@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")
public class User {private int id;private User friend; // 可能循環引用
}
Q2: 日期格式全局配置
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd"));
Q3: 忽略 null 字段
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
總結
Jackson 提供了強大而靈活的 JSON 處理能力:
- 基礎操作:
ObjectMapper
+readValue
/writeValue
- 注解控制:
@JsonProperty
、@JsonIgnore
等 - 高級特性:自定義序列化、泛型處理、Spring 集成
掌握這些用法后,你可以高效安全地處理任何 JSON 數據場景!