Jackson 常用注解与完整用法总结
一、📦 核心注解分类总览
| 注解 | 作用 | 常见用途 |
|---|---|---|
| @JsonSerialize | 自定义字段序列化(对象 → JSON) | Long 转字符串、日期格式化、byte[] 转 Base64 |
| @JsonDeserialize | 自定义字段反序列化(JSON → 对象) | 字符串转日期、Base64 解码、枚举转换 |
| @JsonFormat | 格式化日期、时间、数字 | Date 转 "yyyy-MM-dd HH:mm:ss" |
| @JsonIgnore | 忽略字段 | 不返回密码、敏感信息等 |
| @JsonIgnoreProperties | 忽略多个字段 | 批量屏蔽字段 |
| @JsonInclude | 控制哪些字段参与序列化 | 忽略 null 或空字符串字段 |
| @JsonProperty | 自定义 JSON 字段名 | 数据库字段名和前端字段名不一致 |
| @JsonAlias | 支持多个 JSON 输入字段名映射到同一属性 | 兼容老版本字段名 |
| @JsonGetter / @JsonSetter | 自定义 getter / setter 名称 | 更灵活地控制属性映射 |
| @JsonAnyGetter / @JsonAnySetter | 动态键值映射 | Map 动态字段 |
| @JsonUnwrapped | 展开嵌套对象属性 | 内嵌实体扁平化输出 |
| @JsonView | 分组控制字段可见性 | 区分“用户视图”和“管理员视图” |
二、🔧 @JsonSerialize 用法详解
✅ 1. Long 精度防丢失
JS 最大安全整数是 2^53-1,超出后会丢失精度。
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;public class User {@JsonSerialize(using = ToStringSerializer.class)private Long id;
}
输出:
{"id": "1844674407370955161"}
✅ 2. 日期格式化(自定义序列化器)
@JsonSerialize(using = CustomDateSerializer.class)
private Date createTime;
public class CustomDateSerializer extends JsonSerializer<Date> {@Overridepublic void serialize(Date value, JsonGenerator gen, SerializerProvider serializers) throws IOException {gen.writeString(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(value));}
}
输出:
{"createTime": "2025-10-27 09:30:00"}
✅ 3. byte[] → Base64
@JsonSerialize(using = ByteArrayToBase64Serializer.class)
private byte[] qrCode;
public class ByteArrayToBase64Serializer extends JsonSerializer<byte[]> {@Overridepublic void serialize(byte[] value, JsonGenerator gen, SerializerProvider serializers) throws IOException {gen.writeString(Base64.getEncoder().encodeToString(value));}
}
✅ 4. 自定义对象序列化
比如枚举输出中英文描述:
@JsonSerialize(using = StatusEnumSerializer.class)
private Status status;
public enum Status { RESERVED, BORROWED }public class StatusEnumSerializer extends JsonSerializer<Status> {@Overridepublic void serialize(Status value, JsonGenerator gen, SerializerProvider serializers) throws IOException {String text = switch (value) {case RESERVED -> "已预约";case BORROWED -> "已借出";};gen.writeString(text);}
}
三、🔁 @JsonDeserialize 用法详解
与 @JsonSerialize 相反,用于“反序列化”。
✅ 1. 字符串转日期
@JsonDeserialize(using = CustomDateDeserializer.class)
private Date createTime;
public class CustomDateDeserializer extends JsonDeserializer<Date> {@Overridepublic Date deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {try {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(p.getText());} catch (ParseException e) {throw new RuntimeException(e);}}
}
✅ 2. Base64 → byte[]
@JsonDeserialize(using = Base64ToByteArrayDeserializer.class)
private byte[] qrCode;
public class Base64ToByteArrayDeserializer extends JsonDeserializer<byte[]> {@Overridepublic byte[] deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {return Base64.getDecoder().decode(p.getText());}
}
四、⏱️ @JsonFormat(日期 / 数字格式化)
最常用的简化形式:
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "Asia/Shanghai")
private Date createTime;
五、🔒 @JsonIgnore / @JsonIgnoreProperties
忽略单个字段
@JsonIgnore
private String password;
忽略多个字段
@JsonIgnoreProperties({"password", "salt"})
public class User { ... }
六、🧹 @JsonInclude(控制空值输出)
@JsonInclude(JsonInclude.Include.NON_NULL)
private String description; // null 时不会输出
常用枚举值:
| 值 | 含义 |
|---|---|
| ALWAYS | 总是输出 |
| NON_NULL | 忽略 null |
| NON_EMPTY | 忽略 null 和 "" |
| NON_DEFAULT | 忽略默认值 |
七、🪶 @JsonProperty / @JsonAlias
@JsonProperty("user_name")
private String username;
输出:
{"user_name": "阿杰"}
支持旧字段名兼容输入:
@JsonAlias({"userName", "user_name"})
private String username;
八、🧩 @JsonView(控制字段可见性)
定义视图接口:
public class Views {public interface UserView {}public interface AdminView extends UserView {}
}
在实体中标注:
@JsonView(Views.UserView.class)
private String name;@JsonView(Views.AdminView.class)
private String password;
控制输出:
@GetMapping("/user")
@JsonView(Views.UserView.class)
public User getUser() { return user; }
九、🌍 全局配置(无需每个字段标注)
如果你所有 Long 都要转字符串,可在配置类中注册:
@Configuration
public class JacksonConfig {@Beanpublic ObjectMapper objectMapper() {ObjectMapper mapper = new ObjectMapper();SimpleModule module = new SimpleModule();module.addSerializer(Long.class, ToStringSerializer.instance);module.addSerializer(Long.TYPE, ToStringSerializer.instance);mapper.registerModule(module);return mapper;}
}
✅ 这样全项目所有Long自动以字符串输出。
🔚 十、总结表格
| 注解 | 方向 | 用途 | 示例 |
|---|---|---|---|
| @JsonSerialize | 序列化 | 自定义字段转 JSON | Long→String |
| @JsonDeserialize | 反序列化 | JSON 转字段 | String→Date |
| @JsonFormat | 序列化+反序列化 | 格式化日期数字 | Date 格式 |
| @JsonIgnore | 序列化+反序列化 | 忽略字段 | 隐藏密码 |
| @JsonInclude | 序列化 | 过滤空字段 | null 不输出 |
| @JsonProperty | 双向 | 字段重命名 | name→user_name |
| @JsonAlias | 反序列化 | 多别名输入 | userName, user_name |
| @JsonView | 序列化 | 视图控制 | 区分权限 |
| @JsonUnwrapped | 序列化 | 展开嵌套对象 | 地址扁平化输出 |
