Jackson 处理 JSON 生成与解析指南

37 阅读2分钟

1. 核心依赖

Spring Boot 默认集成 Jackson,无需额外依赖:

<!-- 如果使用 Spring Boot Starter Web -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

2. 基础用法

2.1 对象转 JSON 序列化
ObjectMapper mapper = new ObjectMapper();
User user = new User("张三", 25);
String json = mapper.writeValueAsString(user);
// 输出:{"name":"张三","age":25}
2.2 JSON 转对象(反序列化)
String json = "{"name":"李四","age":30}";
User user = mapper.readValue(json, User.class);

3. 常用注解

3.1 字段控制
public class User {
    @JsonProperty("user_name")  // 自定义JSON字段名
    private String name;

    @JsonIgnore  // 忽略字段
    private String password;

    @JsonInclude(JsonInclude.Include.NON_NULL)  // 非空时序列化
    private String email;
}
3.2 时间格式
public class Order {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
    private LocalDateTime createTime;
}
3.3 多态处理
@JsonTypeInfo(use = Id.NAME, property = "type")
@JsonSubTypes({
    @Type(value = Cat.class, name = "cat"),
    @Type(value = Dog.class, name = "dog")
})
public abstract class Animal {}

4. 自定义配置(Spring Boot)

4.1 全局配置
@Configuration
public class JacksonConfig {

    @Bean
    public ObjectMapper objectMapper() {
        return new ObjectMapper()
            .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)  // 日期不转时间戳
            .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);
    }
}
4.2 配置项 示例
# application.yml
spring:
  jackson:
    date-format: yyyy-MM-dd HH:mm:ss
    time-zone: GMT+8
    default-property-inclusion: non_null
    deserialization:
      FAIL_ON_UNKNOWN_PROPERTIES: false  # 忽略未知字段

5. 高级技巧

5.1 处理 泛型
TypeReference<ResultDTO<List<User>>> typeRef = new TypeReference<>() {};
ResultDTO<List<User>> result = mapper.readValue(json, typeRef);
5.2 流式 API (处理大文件)
JsonFactory factory = mapper.getFactory();
try (JsonParser parser = factory.createParser(new File("large.json"))) {
    while (parser.nextToken() != null) {
        // 逐条处理
    }
}
5.3 自定义 序列化
public class MoneySerializer extends JsonSerializer<BigDecimal> {
    @Override
    public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider) {
        gen.writeString(value.setScale(2, RoundingMode.HALF_UP) + "元");
    }
}

// 使用注解
public class Product {
    @JsonSerialize(using = MoneySerializer.class)
    private BigDecimal price;
}

6. 常见问题解决

6.1 循环引用问题
// 方法1:使用 @JsonIgnore 打断循环
public class Order {
    @JsonIgnore
    private User user;
}

// 方法2:配置全局忽略
mapper.configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
6.2 枚举处理
public enum Status {
    @JsonValue  // 序列化时使用 code
    OK(1), ERROR(2);

    private final int code;
    // 反序列化时根据 code 转换
    @JsonCreator
    public static Status fromCode(int code) { /* ... */ }
}
6.3 处理特殊字符
mapper.configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
// 输入:{"name":"张三"} → 输出:{"name":"\u5F20\u4E09"}

7. 性能优化

7.1 启用缓存
mapper.enable(MapperFeature.USE_ANNOTATIONS);
mapper.enable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
7.2 线程安全 配置
ObjectMapper mapper = new ObjectMapper();
// 配置为线程安全
mapper.registerModule(new JavaTimeModule());
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
7.3 使用第三方模块
<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());

8. 安全注意事项

8.1 防止 XXE 攻击
mapper.configure(JsonParser.Feature.ALLOW_EXTERNAL_PROCESSING, false);
8.2 反序列化防护
// 启用类型检查
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
// 或使用注解 @JsonTypeInfo

最佳实践 总结

  1. 统一配置:通过 ObjectMapper 全局配置确保一致性

  2. 合理使用注解:避免过度注解导致代码污染

  3. 性能监控:对高频接口进行序列化性能测试

  4. 版本管理:及时升级 Jackson 版本修复漏洞

通过以上方法,可以高效安全地处理 JSON 数据。