如何使用Gson在Java中解析指定格式的JSON文件?
使用Gson解析目标JSON文件的完整实现方案
我来帮你把这个解析流程补全并梳理清楚,按照你的需求一步步来:
1. 定义对应JSON结构的Java实体类
首先得把JSON的层级结构映射成Java类,你的JSON最外层是包含parcel数组的对象,数组里的每个元素是用户信息,所以我们需要两个类来对应:
import java.util.List; // 根类,对应最外层JSON结构(包裹parcel数组) class ParcelContainer { private List<Person> parcel; // Gson需要Getter/Setter来完成字段映射,也可以用public字段,推荐用封装方式 public List<Person> getParcel() { return parcel; } public void setParcel(List<Person> parcel) { this.parcel = parcel; } } // 用户信息类,对应parcel数组里的每个元素 class Person { private String firstName; private String lastName; private String email; private String country; private List<String> dates; // 生成所有字段的Getter/Setter方法 public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getCountry() { return country; } public void setCountry(String country) { this.country = country; } public List<String> getDates() { return dates; } public void setDates(List<String> dates) { this.dates = dates; } }
2. 确保引入Gson依赖
如果是Maven项目,在pom.xml里添加Gson依赖:
<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'
3. 完善main方法的解析逻辑
你已经写了try(Reader rea...的开头,我们把这部分补全,完成文件读取和JSON解析:
import com.google.gson.Gson; import java.io.FileReader; import java.io.IOException; import java.io.Reader; public class JsonParserDemo { public static void main(String[] args) throws IOException { // 初始化Gson实例 Gson gson = new Gson(); // 用try-with-resources自动关闭Reader,避免资源泄漏 try (Reader reader = new FileReader("你的JSON文件绝对路径或相对路径")) { // 将JSON解析为根类对象 ParcelContainer container = gson.fromJson(reader, ParcelContainer.class); // 遍历解析后的结果,验证数据 for (Person person : container.getParcel()) { System.out.println("姓名: " + person.getFirstName() + " " + person.getLastName()); System.out.println("邮箱: " + person.getEmail()); System.out.println("国家: " + person.getCountry()); System.out.println("关联日期: " + person.getDates()); System.out.println("------------------------"); } } catch (IOException e) { // 捕获文件读取异常并打印 e.printStackTrace(); } } }
关键注意点:
- 把代码里的文件路径替换成你实际的JSON文件路径(支持绝对路径或项目相对路径)
- Gson会自动匹配JSON字段和Java类的字段名,注意大小写敏感
- 用
try-with-resources语法可以确保Reader自动关闭,不用手动写close()
内容的提问来源于stack exchange,提问作者Niras
相关产品推荐
相关产品推荐

