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

Java实现类似JS/PHP的关联数组式JSON读取:数组读取问题求助

实现Java中类似JS/PHP的关联数组式JSON读取(解决数组访问问题)

嘿,看起来你已经快搞定这个需求了!在Java里实现像JS/PHP那样用['key']['subKey']或者['array'][index]的链式语法读取JSON,核心痛点就是Java的强类型特性——JSONObject和JSONArray是完全分开的类,没法直接无缝链式调用。针对你遇到的数组读取问题,我给你一个完整的解决方案,基于常用的org.json库来实现:

第一步:封装统一的JSON访问工具类

我们可以写一个JsonAccessor类,它内部持有当前的JSON节点(可能是JSONObject或JSONArray),对外提供重载的get方法,让你既能用键访问对象,也能用索引访问数组,并且返回JsonAccessor实例支持链式调用。

import org.json.JSONArray;
import org.json.JSONObject;

public class JsonAccessor {
    private final Object currentNode;

    // 构造方法:支持从JSONObject或JSONArray初始化
    public JsonAccessor(Object node) {
        if (!(node instanceof JSONObject || node instanceof JSONArray)) {
            throw new IllegalArgumentException("仅支持JSONObject或JSONArray类型");
        }
        this.currentNode = node;
    }

    // 访问JSON对象的键,返回新的JsonAccessor
    public JsonAccessor get(String key) {
        if (!(currentNode instanceof JSONObject)) {
            throw new IllegalStateException("当前节点不是JSON对象,无法通过键访问");
        }
        JSONObject obj = (JSONObject) currentNode;
        Object value = obj.get(key);
        return new JsonAccessor(value);
    }

    // 访问JSON数组的索引,返回新的JsonAccessor
    public JsonAccessor get(int index) {
        if (!(currentNode instanceof JSONArray)) {
            throw new IllegalStateException("当前节点不是JSON数组,无法通过索引访问");
        }
        JSONArray arr = (JSONArray) currentNode;
        Object value = arr.get(index);
        return new JsonAccessor(value);
    }

    // 获取最终的实际值(比如String、Number等)
    public <T> T getValue() {
        @SuppressWarnings("unchecked")
        T value = (T) currentNode;
        return value;
    }
}

第二步:使用工具类读取你的JSON数据

假设你已经把data.json的内容读取成了字符串jsonStr,我们可以这样用:

import org.json.JSONObject;

public class Main {
    public static void main(String[] args) {
        // 这里替换成你的data.json内容字符串
        String jsonStr = "{ \"students\": { \"2334\": { \"name\": { \"firstname\": \"umer\", \"lastname\": \"farooq\" }, \"subject\": { \"marks\": { \"maths\": { \"total\": 100.0, \"obtained\": 70.0 }, \"computer\": { \"total\": 100.0, \"obtained\": 96.0 } } }, \"lang\": [\"java\", \"javascript\", \"C#\"] }, \"1003\": { \"name\": { \"firstname\": \"john\" } } }";
        
        // 初始化根节点的JsonAccessor
        JsonAccessor root = new JsonAccessor(new JSONObject(jsonStr));

        // 读取对象属性:比如获取umer的firstname
        String firstName = root.get("students").get("2334").get("name").get("firstname").getValue();
        System.out.println("First Name: " + firstName); // 输出 umer

        // 读取数组元素:比如获取lang数组的第二个元素
        String secondLang = root.get("students").get("2334").get("lang").get(1).getValue();
        System.out.println("Second Language: " + secondLang); // 输出 javascript

        // 读取数值:比如获取computer的obtained分数
        Double computerMarks = root.get("students").get("2334").get("subject").get("marks").get("computer").get("obtained").getValue();
        System.out.println("Computer Obtained Marks: " + computerMarks); // 输出 96.0
    }
}

第三步:处理依赖

如果你用Maven,需要在pom.xml里添加org.json的依赖:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20231013</version> <!-- 用最新版本即可 -->
</dependency>

为什么这个方案能解决你的问题?

你之前遇到的数组访问问题,本质是Java中JSONObject没有数组索引的方法,JSONArray也没有键访问的方法。这个JsonAccessor类帮你做了类型判断和转换,对外提供了统一的调用方式,让你能像JS/PHP那样链式访问任意JSON节点——不管是对象还是数组。

另外,你可以根据自己的需求扩展这个类:比如添加opt方法(避免键不存在抛出异常)、支持更多类型的自动转换等。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:29:54