本 Jackson 教程将教你使用 Jackson ObjectMapper 读取和写入 JSON 数据到 Java 对象。
1. 设置 Jackson
为了在项目中包含 Jackson 库,我们应该包含 jackson-databind 依赖,该依赖内部会拉取其他两个需要的依赖,即 jackson-annotations 和 jackson-core。
我们可以在 maven 站点找到最新版本。
<properties>
<jackson.version>2.13.0</jackson.version>
</properties>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
implementation 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
导入 Jackson 后,我们可以开始使用 ObjectMapper 类进行序列化和反序列化 JSON。
ObjectMapper mapper = new ObjectMapper();
//Java Object -> JSON
String json = mapper.writeValueAsString(pojoInstance);
//JSON -> Java Object
Pojo instance = mapper.readValue(json, Pojo.class);
2. ObjectMapper 类
ObjectMapper 是用于数据绑定的主要类。 它带有几个读取器/写入器方法来执行 Java 和 JSON 之间的转换。 它将使用 JsonParser 和 JsonGenerator 的实例来实现实际的 JSON 读取/写入。
ObjectMapper 提供了以两种形式读取和写入 JSON 的功能
- 到和从基本的 POJO
- 到和从通用的 JSON 树模型
ObjectMapper 也充当更高级的 ObjectReader 和 ObjectWriter 类的工厂。 这些类是 建造者模式 风格的对象,并且几乎与 ObjectMapper 执行相同的操作。 ObjectMapper 实例是 **完全 线程安全** 的,前提是所有实例的配置都在任何读取或写入调用之前发生。
ObjectMapper 类中的主要方法是
- canDeserialize(Class type) – 检查映射器是否可以反序列化给定类的实例。
- canSerialize(Class type) – 检查映射器是否可以序列化给定类的实例。
- configure(SerializationFeature f, boolean state) – 更改序列化功能的开启/关闭状态。
- configure(DeserializationFeature f, boolean state) – 更改反序列化功能的开启/关闭状态。
- configure(JsonParser.Feature f, boolean state) – 更改解析器实例的指定功能的状态。
- copy() – 创建与原始实例具有相同初始配置的新 ObjectMapper 实例。
- readValue() – **从各种来源读取 JSON,例如字节数组、File、InputStream、Reader、URL 或 String。**
- writeValue() – **用于序列化 JSON 到各种格式,例如 OutputStream、Writer、POJO 或 File。**
3. 将 Java 对象序列化为 JSON
3.1. 简单用法
Jackson 在将简单的 POJO 对象转换为 JSON 字符串时,通常非常直接。它只涉及两个步骤
- 创建
com.fasterxml.jackson.databind.ObjectMapper的实例 - 使用
objectMapper.writeValueAsString()方法将 POJO 转换为 JSON
public class Article
{
private Long id;
private String title;
private List<String> tags;
//Setters, getters and constructors are hidden for brevity
}
ObjectMapper mapper = new ObjectMapper();
Article article = new Article(1L, "Test Title", Collections.singletonList("Test Tag"));
String json = mapper.writeValueAsString(article);
System.out.println(json); //{"id":1,"title":"Test Title","tags":["Test Tag"]}
3.2. 格式化输出
要获得格式化的 JSON 字符串,请使用 writerWithDefaultPrettyPrinter() 方法获取启用格式化输出的写入器实例。或者,我们可以在 ObjectMapper 类中简单地启用 SerializationFeature.INDENT_OUTPUT。
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(article);
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper..writeValueAsString(article);
4. 将 JSON 反序列化为 Java 对象
4.1. 从字符串读取
与写入操作类似,将 JSON 读取到 Java 对象也相当简单。我们需要使用 ObjectMapper 的 readValue() 方法。
String json = "{\"id\":1,\"title\":\"Test Title\",\"tags\":[\"Test Tag\"]}";
ObjectMapper mapper = new ObjectMapper();
Article newArticle = mapper.readValue(json, Article.class);
System.out.println(newArticle); //Article [id=1, title=Test Title, tags=[Test Tag]]
4.2. 从 JSON 文件读取
从文件读取 JSON 到 Java 对象也与前面的示例非常相似。我们需要使用 ObjectMapper 的 readValue() 方法。
我们只需要将 readValue() 方法的第一个参数替换为 File 实例即可。
更多信息:从资源文件夹读取文件
ObjectMapper mapper = new ObjectMapper();
//Reads the file from resources folder
URL url = Jackson2Demo.class.getClassLoader().getResource("article.json");
Article article = mapper.readValue(new File(url.getFile()), Article.class);
System.out.println(article);
祝您学习愉快!!
评论