当前位置: 首页 > news >正文

Jackson 使用方法详解

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. 性能优化建议

  1. 重用 ObjectMapper
    避免重复创建,推荐作为单例使用。

  2. 使用 TypeReference 处理泛型

    List<Person> people = mapper.readValue(json, new TypeReference<List<Person>>() {});
    
  3. 启用缓存

    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 数据场景!

相关文章:

  • 操作系统八股问——连载ing
  • 具身智能机器人的应用场景及最新进展
  • 解决MacOS端口被占用问题
  • 安卓基础(接口interface)
  • 高压场景首选:CKESC ROCK 120A-H CAN 电调技术解析与实测报告
  • 51c大模型~合集122
  • 第十六节:开放性问题-Vue与React Hooks对比
  • vue3:v-model的原理示例
  • ISO-C99标准 最小限定值
  • 驱动开发硬核特训 │ Regulator 子系统全解
  • IDEA2022.3开启热部署
  • 【React Native】精通 react native
  • 假云阴影模拟
  • 数字孪生三维建模+虚拟仿真,构建可预测的未来工厂
  • QT采用mqtt进行通信(17.1)
  • 小波变换和图像的融合
  • 征程 6 逆向自证 hbm 与 bc 一致性
  • Spring系列五:手动实现Spring底层机制 第一部分
  • 在 Conda 中,包的安装路径在电脑的哪里
  • SwiftUI 10.Toggle介绍和使用
  • 汪明荃,今生不负你
  • 视频|漫画家寂地:古老丝路上的文化与交流留下的独特印记
  • 加力、攻坚、借力、问效,上海为优化营商环境推出增量举措
  • 习近平《在庆祝中华全国总工会成立100周年暨全国劳动模范和先进工作者表彰大会上的讲话》单行本出版
  • 哥伦比亚总统称将在访华期间签署“一带一路”倡议意向书,外交部回应
  • 解读|降准叠加政策利率、公积金贷款利率、结构性政策工具利率全线下调,影响有多大?