現代項目建議使用 Maven/Gradle 管理依賴,避免手動導入 JAR 包:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.41</version>
</dependency>
public class Emp {
private Integer id;
private String name;
private Integer dptNo;
private String gender;
private String duty;
// 省略 Getter/Setter,建議使用 Lombok @Data
}
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonDemo {
private static final ObjectMapper MAPPER = new ObjectMapper(); // 線程安全,可復用
public static <T> String toJson(T obj) {
try {
return MAPPER.writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException("JSON 序列化失敗", e);
}
}
public static void main(String[] args) {
Emp emp = new Emp();
emp.setId(1);
emp.setName("張三");
emp.setGender("男");
emp.setDptNo(1);
emp.setDuty("職員");
String json = toJson(emp);
System.out.println(json);
// 輸出: {"id":1,"name":"張三","dptNo":1,"gender":"男","duty":"職員"}
}
}
// 忽略 NULL 字段
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// 日期格式化
mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
// 驼峰轉下劃線
mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
import com.alibaba.fastjson.JSON;
public class FastjsonDemo {
public static void main(String[] args) {
Emp emp = new Emp();
emp.setId(1);
emp.setName("李四");
emp.setGender("女");
emp.setDptNo(2);
emp.setDuty("經理");
String json = JSON.toJSONString(emp);
System.out.println(json);
// 輸出: {"dptNo":2,"duty":"經理","gender":"女","id":1,"name":"李四"}
}
}
@JSONField(name = "dept_no") // 指定 JSON 字段名 private Integer dptNo; @JSONField(format = "yyyy-MM-dd") // 日期格式化 private Date createTime; @JSONField(serialize = false) // 忽略序列化 private String password;
| 維度 | Jackson | Fastjson |
|---|---|---|
| 生態地位 | Spring Boot 默認、Java EE 標準 | 國內廣泛使用、阿里維護 |
| 序列化性能 | 優(2.x 大幅優化) | 極優(針對性優化) |
| 功能豐富度 | 極強(模塊化擴展、樹模型、流式) | 強(注解驅動、TypeReference) |
| 安全性 | 高(默認關閉自動類型) | 需注意 autoType 風險(2.x 已修復) |
| 遷移成本 | 低(標準 API) | 低(API 相似) |
ObjectMapper Bean,零配置即用ParserConfig.getGlobalInstance().setAutoTypeSupport(false)JsonUtils 工具類,業務代碼無感切換net.sf.json(舊版 json-lib)與 Jackson,且重複序列化,切勿參考Jackson 與 Fastjson 均為成熟可靠的 JSON 庫。現代 Spring 生態首選 Jackson,追求極致性能或存量項目可用 Fastjson 2.x。核心原則:統一工具類封裝、合理配置序列化策略、拒絕混用多庫。