You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java从JSON文件解析JSON数组:Gson与json-simple使用指导求助

嘿,完全理解你中断编程后重新捡起来的那种生疏感,基础问题一点都不用不好意思!我给你整理了用Gson和json-simple逐行读取JSON文件并提取值的清晰方案,附详细解析,帮你快速上手~


用Gson逐行读取JSON文件

Gson是谷歌推出的JSON处理库,语法简洁,支持实体类映射,非常适合结构固定的JSON场景。

1. 先引入依赖(Maven为例)

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version> <!-- 建议用最新稳定版 -->
</dependency>

2. 代码实现(两种常用方式)

假设你的JSON文件每行是一个独立的JSON对象,比如:

{"id":1,"name":"Alice"}
{"id":2,"name":"Bob"}

方式一:实体类映射(类型安全推荐)

提前定义和JSON结构匹配的实体类,Gson会自动完成映射:

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

// 定义对应JSON结构的实体类
class User {
    private int id;
    private String name;

    // 必须添加无参构造器,Gson反射创建对象需要它
    public User() {}

    // Getter方法,用于提取值
    public int getId() { return id; }
    public String getName() { return name; }
}

public class GsonLineReader {
    public static void main(String[] args) {
        String filePath = "your-file-path.json";
        Gson gson = new Gson();

        // try-with-resources语法:自动关闭流,避免资源泄漏
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            // 逐行读取文件
            while ((line = br.readLine()) != null) {
                // 跳过空行
                if (line.trim().isEmpty()) continue;

                // 将JSON字符串转成实体类
                User user = gson.fromJson(line, User.class);
                // 提取并打印值
                System.out.println("ID: " + user.getId() + ", 姓名: " + user.getName());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

方式二:Map映射(灵活适配多变结构)

如果JSON结构不固定,不想写实体类,可以转成Map来取值:

import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

public class GsonMapReader {
    public static void main(String[] args) {
        String filePath = "your-file-path.json";
        Gson gson = new Gson();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                // 转成Map<String, Object>
                Map<String, Object> userMap = gson.fromJson(line, Map.class);
                // 注意:Gson会把JSON整数转成Double,需要手动转成int
                int id = ((Double) userMap.get("id")).intValue();
                String name = (String) userMap.get("name");
                System.out.println("ID: " + id + ", 姓名: " + name);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 关键解析

  • try-with-resources:Java 7+的语法,自动关闭BufferedReader,不用手动写close(),避免资源泄漏。
  • 实体类方式:类型安全,不会出现类型转换错误,适合固定结构的JSON。
  • Map方式:灵活度高,但要注意Gson的类型转换规则(比如整数转Double)。

用json-simple逐行读取JSON文件

json-simple是轻量级的JSON处理库,API更底层,适合不需要实体类的简单场景。

1. 引入依赖(Maven为例)

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

2. 代码实现

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class JsonSimpleLineReader {
    public static void main(String[] args) {
        String filePath = "your-file-path.json";
        JSONParser parser = new JSONParser();

        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String line;
            while ((line = br.readLine()) != null) {
                if (line.trim().isEmpty()) continue;

                try {
                    // 解析每行JSON成JSONObject
                    JSONObject jsonObj = (JSONObject) parser.parse(line);
                    // 提取值:json-simple会把整数转成Long,字符串直接是String
                    long id = (long) jsonObj.get("id");
                    String name = (String) jsonObj.get("name");
                    System.out.println("ID: " + id + ", 姓名: " + name);
                } catch (ParseException e) {
                    // 捕获解析错误,避免某行JSON非法导致整个程序崩溃
                    System.err.println("解析JSON行出错:" + line);
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

3. 关键解析

  • JSONParser.parse():负责将JSON字符串转成JSONObject,需要捕获ParseException处理非法JSON行。
  • 类型转换:json-simple的整数会被解析成Long,字符串直接是String,必须手动强转。
  • 轻量级:库体积小,适合不需要复杂功能的简单场景。

方案选择建议
  • 如果JSON结构固定,优先选Gson实体类方式,代码更简洁且类型安全。
  • 如果JSON结构多变或不想写实体类,Gson Map方式或json-simple都可以,后者更轻量但需要手动处理类型转换。

内容的提问来源于stack exchange,提问作者Zee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:25:08