Loading...
Loading...
Jackson JSON 序列化技能。覆盖日期格式配置(非ISO-8601)、Null序列化规则(数组→[]/字符串→""/数字→null)、@JsonView分层、ObjectMapper单例规则、TypeReference泛型反序列化、@JsonProperty/@JsonFormat/@JsonIgnore注解原则、与Spring Boot集成。 当用户处理JSON序列化/反序列化、配置ObjectMapper、解决日期格式或null处理问题时使用。
npx skill4agent add full-stack-skills/java-skills jackson-patterns编码 Jackson 的使用规则。LLM 默认配置 SerializationFeature.WRITE_DATES_AS_TIMESTAMPS=true,但中国开发者期望 yyyy-MM-dd HH:mm:ss。
| # | 错误 | 正确做法 |
|---|---|---|
| 1 | 日期序列化为时间戳 | 配置 |
| 2 | null 字段不返回或返回 null | 明确规则:数组→[]、字符串→""、数字→null、布尔→null |
| 3 | 每次 new ObjectMapper() | ObjectMapper 是线程安全的,应用级单例 |
| 4 | | |
| 5 | 标准JSON格式不与其他系统对齐 | 带 NullNode/WRITE_BIGDECIMAL_AS_PLAIN 等需要显式配置 |
// ✅ Spring Boot 配置(ObjectMapper全局)
@Configuration
public class JacksonConfig {
@Bean
public Jackson2ObjectMapperBuilderCustomizer customizer() {
return builder -> builder
.simpleDateFormat("yyyy-MM-dd HH:mm:ss")
.serializationInclusion(JsonInclude.Include.NON_NULL)
.featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.featuresToEnable(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES);
}
}
// ✅ 注解方式
@Data
public class UserVO {
@JsonProperty("user_name") // JSON字段重命名
private String username;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
private LocalDateTime createTime;
@JsonIgnore // 序列化时忽略
private String password;
@JsonView(Views.Detail.class) // 仅详情视图返回
private String email;
}
// ✅ TypeReference 反序列化
List<User> users = objectMapper.readValue(json,
new TypeReference<List<User>>(){});
// ✅ Null值处理规则
objectMapper.configOverride(String.class)
.setInclude(JsonInclude.Value.construct(
JsonInclude.Include.NON_NULL, // null string → null
JsonInclude.Include.NON_NULL
));