Java中的JSON处理:数据解析与序列化

面向初学者的在线Python训练器

轻松学习Python,无需理论负担。在浏览器中直接解决带自动检查的实践任务,无需安装任何东西。

开始课程

Java中处理JSON的入门介绍



JSON(JavaScript对象表示法)是一种轻量级数据交换格式,广泛应用于现代Web应用、API和微服务中。尽管名称如此,JSON并不依赖于JavaScript,并且在Java中得到了良好的支持。在本文中,我们将深入探讨如何使用流行的库:Jackson和Gson,在Java中执行JSON的解析、序列化和反序列化。



处理JSON的能力是Java开发者的必备技能。无论是读取配置文件、与REST API交互,还是在微服务之间传输数据——JSON无处不在。我们将介绍这两种方法,以便您能为项目选择最合适的方式。



Java中处理JSON的主要库



在Java生态系统中,有多个流行的JSON处理库。其中两个是事实上的标准:



  • Jackson — 最流行的库,内置于Spring Boot中。它具有高性能和丰富的自定义选项。
  • Gson — 来自Google的库,使用简单且轻量。适合小型项目。


两个库都支持完整的JSON处理周期:序列化(对象 → JSON)、反序列化(JSON → 对象)以及流式处理。



添加依赖



要使用这些库,您需要将它们添加到项目中。如果您使用的是Maven,请在pom.xml中添加以下依赖:



<!-- Jackson --><dependency>    <groupId>com.fasterxml.jackson.core</groupId>    <artifactId>jackson-databind</artifactId>    <version>2.15.2</version></dependency>

<!-- Gson --><dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.10.1</version></dependency>


对于Gradle,请在build.gradle中添加以下行:



implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2'implementation 'com.google.code.gson:gson:2.10.1'


Java对象到JSON的序列化



序列化是将Java对象转换为JSON字符串的过程。让我们看看两种方法。



使用Jackson进行序列化



Jackson使用ObjectMapper类进行序列化。示例:



import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.core.JsonProcessingException;

public class JacksonSerialization { public static void main(String[] args) throws JsonProcessingException { // 创建一个对象用于序列化 User user = new User("Ivan", "ivan@example.com", 25); // 创建ObjectMapper ObjectMapper mapper = new ObjectMapper(); // 序列化为JSON String json = mapper.writeValueAsString(user); System.out.println(json); // 输出: {"name":"Ivan","email":"ivan@example.com","age":25} }}

class User { private String name; private String email; private int age; // 构造函数、getter和setter public User(String name, String email, int age) { this.name = name; this.email = email; this.age = age; } public String getName() { return name; } public String getEmail() { return email; } public int getAge() { return age; }}


使用Gson进行序列化



Gson使用带有toJson()方法的Gson类:



import com.google.gson.Gson;

public class GsonSerialization { public static void main(String[] args) { User user = new User("Maria", "maria@example.com", 30); Gson gson = n

博客

书籍推荐