Java读取JSON文件的完整指南
在Java开发中,JSON(JavaScript Object Notation)作为一种轻量级的数据交换格式,广泛应用于配置文件、接口数据传输、数据存储等场景,如何在Java中读取JSON文件,是开发者的必备技能,本文将详细介绍多种读取JSON文件的方法,从基础到进阶,涵盖不同JSON库的使用,并附上完整代码示例,帮助你快速上手。
准备工作:添加JSON库依赖
在Java中读取JSON文件,通常需要借助第三方JSON库,目前主流的JSON库包括:
- Gson(Google开发,简单易用)
- Jackson(功能强大,性能优秀,Spring框架默认集成)
- org.json(轻量级,API简洁)
以Maven项目为例,首先在pom.xml中添加对应依赖(以Gson和Jackson为例):
Gson依赖
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.10.1</version>
</dependency>
Jackson依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
org.json依赖
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>20231013</version>
</dependency>
准备JSON文件示例
假设我们有一个名为user.json的JSON文件,内容如下(位于项目resources目录下):
{
"name": "张三",
"age": 25,
"isStudent": false,
"courses": [
{"courseName": "Java编程", "credit": 4},
{"courseName": "数据库原理", "credit": 3}
],
"address": {
"city": "北京",
"district": "海淀区"
}
}
使用Gson读取JSON文件
Gson是Google提供的JSON处理库,核心类是Gson,支持将JSON字符串与Java对象互相转换。
读取JSON文件并解析为Java对象(反序列化)
步骤:
- 创建
Gson实例; - 通过
Files读取JSON文件内容为字符串; - 使用
Gson的fromJson()方法将字符串转为Java对象。
代码示例:
首先定义与JSON结构对应的Java类(POJO):
// 课程类
class Course {
private String courseName;
private int credit;
// 无参构造器、getter/setter、toString()方法(省略,实际开发中需添加)
}
// 地址类
class Address {
private String city;
private String district;
// 无参构造器、getter/setter、toString()方法(省略)
}
// 用户类(包含嵌套对象和列表)
class User {
private String name;
private int age;
private boolean isStudent;
private List<Course> courses;
private Address address;
// 无参构造器、getter/setter、toString()方法(省略)
}
读取JSON文件并解析:
import com.google.gson.Gson;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class GsonReadJsonExample {
public static void main(String[] args) {
// 1. 创建Gson实例
Gson gson = new Gson();
try {
// 2. 读取JSON文件内容为字符串
String jsonContent = new String(Files.readAllBytes(Paths.get("src/main/resources/user.json")));
// 3. 解析为User对象
User user = gson.fromJson(jsonContent, User.class);
// 4. 输出结果
System.out.println("用户信息:" + user);
System.out.println("姓名:" + user.getName());
System.out.println("年龄:" + user.getAge());
System.out.println("课程列表:" + user.getCourses());
System.out.println("地址:" + user.getAddress().getCity() + "-" + user.getAddress().getDistrict());
} catch (IOException e) {
System.err.println("读取JSON文件失败:" + e.getMessage());
}
}
}
读取JSON文件并解析为JsonElement(树模型)
如果JSON结构复杂,或无需提前定义Java类,可以使用Gson的JsonElement(树模型)遍历JSON数据。
代码示例:
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class GsonJsonElementExample {
public static void main(String[] args) {
try {
// 1. 读取JSON文件内容
String jsonContent = new String(Files.readAllBytes(Paths.get("src/main/resources/user.json")));
// 2. 解析为JsonElement
JsonElement jsonElement = JsonParser.parseString(jsonContent);
// 3. 转换为JsonObject并遍历
if (jsonElement.isJsonObject()) {
JsonObject jsonObject = jsonElement.getAsJsonObject();
// 获取基本类型字段
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
boolean isStudent = jsonObject.get("isStudent").getAsBoolean();
System.out.println("姓名:" + name + ",年龄:" + age + ",是否学生:" + isStudent);
// 获取数组字段
System.out.println("课程列表:");
jsonObject.getAsJsonArray("courses").forEach(courseElement -> {
JsonObject courseObj = courseElement.getAsJsonObject();
String courseName = courseObj.get("courseName").getAsString();
int credit = courseObj.get("credit").getAsInt();
System.out.println(" - " + courseName + "(学分:" + credit + ")");
});
// 获取嵌套对象
JsonObject addressObj = jsonObject.getAsJsonObject("address");
String city = addressObj.get("city").getAsString();
String district = addressObj.get("district").getAsString();
System.out.println("地址:" + city + "-" + district);
}
} catch (IOException e) {
System.err.println("读取JSON文件失败:" + e.getMessage());
}
}
}
使用Jackson读取JSON文件
Jackson是当前最流行的JSON库之一,功能强大,支持流式解析、树模型、数据绑定等多种方式,且性能优异。
使用ObjectMapper读取JSON文件(数据绑定)
ObjectMapper是Jackson的核心类,用于实现JSON与Java对象的转换。
代码示例:
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
import java.util.List;
public class JacksonReadJsonExample {
public static void main(String[] args) {
// 1. 创建ObjectMapper实例
ObjectMapper objectMapper = new ObjectMapper();
try {
// 2. 读取JSON文件并解析为User对象
User user = objectMapper.readValue(new File("src/main/resources/user.json"), User.class);
// 3. 输出结果
System.out.println("用户信息:" + user);
System.out.println("姓名:" + user.getName());
System.out.println("年龄:" + user.getAge());
System.out.println("是否学生:" + user.isStudent());
System.out.println("课程数量:" + user.getCourses().size());
System.out.println("城市:" + user.getAddress().getCity());
} catch (IOException e) {
System.err.println("读取JSON文件失败:" + e.getMessage());
}
}
}
使用JsonNode读取JSON文件(树模型)
Jackson的JsonNode(树模型)允许灵活遍历JSON结构,无需提前定义Java类。
代码示例:
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.File;
import java.io.IOException;
public class JacksonJsonNodeExample {
public static void main(String[] args) {
ObjectMapper objectMapper = new ObjectMapper();
try {
// 1. 读取JSON文件并解析为JsonNode
JsonNode jsonNode = objectMapper.readTree(new File("src/main/resources/user.json"));
// 2. 遍历JsonNode
// 获取基本类型字段
String name = jsonNode.get("name").asText();
int age = jsonNode.get("age").asInt();
System.out.println("姓名:" + name + ",年龄:" + age);
// 获取数组字段
JsonNode coursesNode = jsonNode.get("courses");
System.out.println("课程列表:");
for (JsonNode courseNode : coursesNode) {
String courseName = courseNode.get("courseName").asText();
int credit = courseNode.get("credit").asInt();
System.out.println(" - " + courseName + "(学分抖音足球直播
抖音足球直播
企鹅直播
企鹅直播
足球直播
爱奇艺直播
爱奇艺足球直播
足球直播
足球直播
iqiyi直播
足球直播
足球直播
QQ足球直播
QQ足球直播
足球直播
足球直播
QQ足球直播
QQ足球直播
足球直播
足球直播
快连
快连
快连
快连下载
快连
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
新浪足球直播
新浪足球直播
足球直播
足球直播
有道翻译
有道翻译
有道翻译
有道翻译
wps
wps
wps
wps
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
足球直播
新浪足球直播
新浪足球直播
足球直播
足球直播



还没有评论,来说两句吧...