Java中的JSON处理:库和工具概述
JSON(JavaScript对象表示法)是一种轻量级的数据交换格式,广泛应用于现代Web应用程序、REST API、配置文件和数据库中。在Java中,有多个强大的库可用于处理JSON,每个库都有其独特的功能、性能和易用性。在本文中,我们将介绍主要工具、它们的功能、代码示例以及最佳实践。
1. Jackson (FasterXML Jackson)
Jackson是Java中最流行且性能最高的JSON处理库。它支持流式处理(类似SAX风格)和对象模型(DOM风格)。Jackson是Spring Boot和许多企业级应用程序的组成部分。
主要功能:
- Java对象与JSON之间的序列化/反序列化
- 大型JSON文件的流式处理(JsonParser, JsonGenerator)
- 支持注解进行精细配置(@JsonProperty, @JsonIgnore, @JsonFormat)
- 节点树操作(JsonNode)
- 支持JSON Schema和验证
代码示例:Jackson的基本使用
import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.JsonNode;
public class JacksonExample { public static void main(String[] args) throws Exception { ObjectMapper mapper = new ObjectMapper();
// 将对象序列化为JSON Person person = new Person("伊万", 30, "ivan@example.com"); String json = mapper.writeValueAsString(person); System.out.println(json); // {"name":"伊万","age":30,"email":"ivan@example.com"}
// 从JSON反序列化为对象 String jsonInput = "{\\"name\\":\\"玛丽亚\\",\\"age\\":25}"; Person deserialized = mapper.readValue(jsonInput, Person.class); System.out.println(deserialized.getName()); // 玛丽亚
// 节点树操作 JsonNode root = mapper.readTree(jsonInput); System.out.println(root.get("age").asInt()); // 25 }}
class Person { private String name; private int age; private String email;
// 构造函数、getter、setter(反序列化必需) public Person() {} public Person(String name, int age, String email) { this.name = name; this.age = age; this.email = email; } // getter和setter...}2. Gson (Google Gson)
Gson是Google开发的库,以其简单性和轻量级著称。它非常适合中小型项目,在这些项目中不需要最高性能。Gson使用反射进行自动序列化/反序列化。
特点:
- 最小配置——开箱即用
- 支持注解(@Expose, @SerializedName)
- 可创建自定义适配器(JsonSerializer, JsonDeserializer)
- 支持集合、数组和嵌套对象
代码示例:Gson的实际应用
import com.google.gson.Gson;import com.google.gson.GsonBuilder;
public class GsonExample { public static void main(String[] args) { Gson gson = new GsonBuilder() .setPrettyPrinting() // 格式化输出 .create();
// 从对象创建JSON Product product = new Product("笔记本电脑", 899.99, true); String json = gson.toJson(product); System.out.println(json);
// 将JSON解析为对象 String jsonInput = "{\\"name\\":\\"鼠标\\",\\"price\\":25.5,\\"available\\":false}"; Product parsed = gson.fromJson(jsonInput, Product.class); System.out.println(parsed.getName()); // 鼠标 }}
class Product {