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

JSON.simple如何正确访问嵌套JSON对象及相关逻辑实现

问题说明

你原本获取嵌套对象的思路方向正确,唯一问题是层级取错:trophy-name不是最外层JSON的属性,而是collection数组中每个子元素的属性,需要在循环内部从每个testObj中提取。

调整后可运行代码

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

public class Main {
    public static void main(String[] args) throws FileNotFoundException, IOException, ParseException {
        JSONParser parser = new JSONParser();
        Object obj = parser.parse(new FileReader("你的json文件路径"));
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray array = (JSONArray) jsonObject.get("collection");

        for (Object item : array) {
            JSONObject testObj = (JSONObject) item;

            // 获取一级属性
            String length = (String) testObj.get("length");
            String pool = (String) testObj.get("pool");
            String weather = (String) testObj.get("weather");
            System.out.println(length);
            System.out.println(pool);
            System.out.println(weather);

            // 获取嵌套的trophy-name对象及内部属性
            JSONObject trophyObj = (JSONObject) testObj.get("trophy-name");
            // 增加非空判断避免空指针
            if (trophyObj != null) {
                String text = (String) trophyObj.get("text");
                String text2 = (String) trophyObj.get("text2");
                System.out.println(text);
                System.out.println(text2);
            }
        }
    }
}

优化建议

  • 你原本的增强for循环写法已经足够简洁,对于json-simple库来说是最优的遍历方式,不需要额外修改。
  • 建议在实际生产环境中给每个字段的获取逻辑都加上非空判断,避免遇到缺失字段的JSON结构时抛出空指针异常。
  • 类名建议按照Java规范首字母大写,你原代码里的main类名不符合规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 15:18:04