准备工作:添加依赖库
你需要先在你的项目中添加相应库的依赖。

(图片来源网络,侵删)
Jackson (推荐)
Jackson 是目前 Java 生态中最流行、性能最好的 JSON 库。
Maven (pom.xml):
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version> <!-- 使用最新版本 -->
</dependency>
Gradle (build.gradle):
implementation 'com.fasterxml.jackson.core:jackson-databind:2.15.2' // 使用最新版本
Google Gson
Gson 是 Google 开发的库,非常易于使用,尤其适合简单的场景。

(图片来源网络,侵删)
Maven (pom.xml):
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version> <!-- 使用最新版本 -->
</dependency>
Gradle (build.gradle):
implementation 'com.google.code.gson:gson:2.10.1' // 使用最新版本
org.json
这是一个轻量级的库,API 简单直接,但功能相对前两者较少。
Maven (pom.xml):

(图片来源网络,侵删)
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20251013</version> <!-- 使用最新版本 -->
</dependency>
Gradle (build.gradle):
implementation 'org.json:json:20251013' // 使用最新版本
将 JSON 字符串转为 JSON 对象 (键值对集合)
假设我们有以下 JSON 字符串:
{
"name": "张三",
"age": 30,
"isStudent": false,
"address": {
"city": "北京",
"street": "中关村大街1号"
},
"hobbies": ["阅读", "旅行", "编程"]
}
方法 1:使用 Jackson
Jackson 会将 JSON 字符串解析为 JsonNode 对象,这是一个通用的 JSON 树模型。
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonStringToJson {
public static void main(String[] args) {
String jsonString = "{\"name\":\"张三\",\"age\":30,\"isStudent\":false,\"address\":{\"city\":\"北京\",\"street\":\"中关村大街1号\"},\"hobbies\":[\"阅读\",\"旅行\",\"编程\"]}";
// 创建 ObjectMapper 实例
ObjectMapper objectMapper = new ObjectMapper();
try {
// 将字符串解析为 JsonNode 对象
JsonNode rootNode = objectMapper.readTree(jsonString);
// 从 JsonNode 中获取数据
String name = rootNode.path("name").asText();
int age = rootNode.path("age").asInt();
boolean isStudent = rootNode.path("isStudent").asBoolean();
System.out.println("姓名: " + name);
System.out.println("年龄: " + age);
System.out.println("是否是学生: " + isStudent);
// 获取嵌套的 JSON 对象
JsonNode addressNode = rootNode.path("address");
String city = addressNode.path("city").asText();
System.out.println("城市: " + city);
// 获取 JSON 数组
JsonNode hobbiesNode = rootNode.path("hobbies");
System.out.print("爱好: ");
for (JsonNode hobby : hobbiesNode) {
System.out.print(hobby.asText() + " ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法 2:使用 Gson
Gson 会将 JSON 字符串解析为 JsonObject 对象。
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
public class GsonStringToJson {
public static void main(String[] args) {
String jsonString = "{\"name\":\"张三\",\"age\":30,\"isStudent\":false,\"address\":{\"city\":\"北京\",\"street\":\"中关村大街1号\"},\"hobbies\":[\"阅读\",\"旅行\",\"编程\"]}";
// 创建 JsonParser 实例
JsonParser parser = new JsonParser();
try {
// 解析字符串为 JsonElement
JsonElement jsonElement = parser.parse(jsonString);
// 转换为 JsonObject
JsonObject jsonObject = jsonElement.getAsJsonObject();
// 从 JsonObject 中获取数据
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
boolean isStudent = jsonObject.get("isStudent").getAsBoolean();
System.out.println("姓名: " + name);
System.out.println("年龄: " + age);
System.out.println("是否是学生: " + isStudent);
// 获取嵌套的 JSON 对象
JsonObject addressObject = jsonObject.getAsJsonObject("address");
String city = addressObject.get("city").getAsString();
System.out.println("城市: " + city);
// 获取 JSON 数组
System.out.print("爱好: ");
for (JsonElement hobby : jsonObject.getAsJsonArray("hobbies")) {
System.out.print(hobby.getAsString() + " ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
方法 3:使用 org.json
这个库直接提供 JSONObject 类。
import org.json.JSONObject;
public class OrgJsonStringToJson {
public static void main(String[] args) {
String jsonString = "{\"name\":\"张三\",\"age\":30,\"isStudent\":false,\"address\":{\"city\":\"北京\",\"street\":\"中关村大街1号\"},\"hobbies\":[\"阅读\",\"旅行\",\"编程\"]}";
try {
// 将字符串直接构造为 JSONObject
JSONObject jsonObject = new JSONObject(jsonString);
// 从 JSONObject 中获取数据
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
boolean isStudent = jsonObject.getBoolean("isStudent");
System.out.println("姓名: " + name);
System.out.println("年龄: " + age);
System.out.println("是否是学生: " + isStudent);
// 获取嵌套的 JSON 对象
JSONObject addressObject = jsonObject.getJSONObject("address");
String city = addressObject.getString("city");
System.out.println("城市: " + city);
// 获取 JSON 数组
System.out.print("爱好: ");
for (Object hobby : jsonObject.getJSONArray("hobbies")) {
System.out.print(hobby + " ");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
将 JSON 字符串转为 Java 对象 (POJO)
这是更常见的需求,特别是与后端 API 交互时,你需要先创建一个与 JSON 结构对应的 Java 类(POJO)。
定义 Java 类 (POJO)
// User.java
public class User {
private String name;
private int age;
private boolean isStudent;
private Address address;
private String[] hobbies;
// Getters and Setters (必须要有)
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
public boolean isStudent() { return isStudent; }
public void setStudent(boolean student) { isStudent = student; }
public Address getAddress() { return address; }
public void setAddress(Address address) { this.address = address; }
public String[] getHobbies() { return hobbies; }
public void setHobbies(String[] hobbies) { this.hobbies = hobbies; }
// (可选) 重写 toString 方法方便打印
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", isStudent=" + isStudent +
", address=" + address +
", hobbies=" + String.join(", ", hobbies) +
'}';
}
}
// Address.java
public class Address {
private String city;
private String street;
// Getters and Setters
public String getCity() { return city; }
public void setCity(String city) { this.city = city; }
public String getStreet() { return street; }
public void setStreet(String street) { this.street = street; }
@Override
public String toString() {
return "Address{" +
"city='" + city + '\'' +
", street='" + street + '\'' +
'}';
}
}
使用 Jackson 进行转换
Jackson 的核心优势就在于此,可以直接映射到 POJO。
import com.fasterxml.jackson.databind.ObjectMapper;
public class JacksonStringToPOJO {
public static void main(String[] args) {
String jsonString = "{\"name\":\"张三\",\"age\":30,\"isStudent\":false,\"address\":{\"city\":\"北京\",\"street\":\"中关村大街1号\"},\"hobbies\":[\"阅读\",\"旅行\",\"编程\"]}";
ObjectMapper objectMapper = new ObjectMapper();
try {
// 直接将字符串映射为 User 对象
User user = objectMapper.readValue(jsonString, User.class);
// 现在你可以像操作普通 Java 对象一样操作 user
System.out.println(user.getName());
System.out.println(user.getAddress().getCity());
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
使用 Gson 进行转换
Gson 同样可以轻松实现。
import com.google.gson.Gson;
public class GsonStringToPOJO {
public static void main(String[] args) {
String jsonString = "{\"name\":\"张三\",\"age\":30,\"isStudent\":false,\"address\":{\"city\":\"北京\",\"street\":\"中关村大街1号\"},\"hobbies\":[\"阅读\",\"旅行\",\"编程\"]}";
Gson gson = new Gson();
try {
// 直接将字符串映射为 User 对象
User user = gson.fromJson(jsonString, User.class);
System.out.println(user.getName());
System.out.println(user.getAddress().getCity());
System.out.println(user);
} catch (Exception e) {
e.printStackTrace();
}
}
}
总结与选择建议
| 特性 | Jackson | Gson | org.json |
|---|---|---|---|
| 易用性 | 中等 (需要理解 ObjectMapper) |
高 (API非常直观) | 高 (API非常简单) |
| 性能 | 高 (业界公认最快) | 高 | 中等 |
| 功能 | 非常强大 (流式 API, 树模型, 数据绑定) | 强大 (数据绑定, 流式 API) | 基础 (树模型操作) |
| 数据绑定 | 最佳 (自动映射到 POJO,支持复杂类型) | 优秀 (自动映射到 POJO) | 不支持 (只能操作 JSON 结构) |
| 生态 | 非常成熟 (Spring Boot 默认使用) | 非常成熟 (Google出品) | 成熟 |
| 推荐场景 | 大型项目、高性能要求、与 Spring Boot 集成 | 快速开发、中小型项目、Android 开发 | 简单的 JSON 解析/构建任务、轻量级需求 |
如何选择?
- 新项目,尤其是企业级或 Web 项目:强烈推荐 Jackson,它是事实上的标准,性能卓越,功能全面,并且是 Spring Boot 的默认选择,学习它非常有价值。
- 快速原型开发或中小型项目:Gson 是一个绝佳的选择,它的 API 设计非常友好,易于上手,对于简单的 JSON 处理非常方便。
- 只需要对 JSON 字符串进行简单的读取或构建,不涉及复杂逻辑或 POJO 映射:org.json 足够用了,它非常轻量,API 简单直接。
对于绝大多数 Java 掌握 Jackson 是必备技能,如果你不确定用哪个,选 Jackson 通常不会错。
