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

Java使用org.json库如何获取JSON数组内无名称JSON对象的值

org.json 解析顶层对象内部数组元素的方案

你可以直接按以下步骤操作:

  • 先将API返回的JSON字符串解析为JSONObject顶层对象
  • 通过顶层对象的getJSONArray()方法,传入数组对应的key lorem拿到目标数组
  • 遍历数组的每个索引,调用getJSONObject(index)即可直接获取数组中没有显式名称的内部JSON对象
  • 从内部对象中按字段名调用对应的get方法即可拿到字段值

完整代码示例:

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

public class ParseDemo {
    public static void main(String[] args) {
        // 替换为实际的API返回JSON字符串
        String apiResponse = """
                {
                  "lorem": [
                   {
                     "ipsum":"dolor",
                     "sit":"amet",
                     "consectetur":"adipiscing"
                   },
                   {
                     "ipsum":"dolor",
                     "sit":"amet",
                     "consectetur":"adipiscing"
                   },
                   {
                     "ipsum":"dolor",
                     "sit":"amet",
                     "consectetur":"adipiscing"
                   }
                  ]
                }
                """;

        // 解析顶层对象
        JSONObject topJson = new JSONObject(apiResponse);
        // 取lorem数组
        JSONArray loremArray = topJson.getJSONArray("lorem");
        // 遍历数组取所有内部对象
        for (int i = 0; i < loremArray.length(); i++) {
            JSONObject innerObj = loremArray.getJSONObject(i);
            // 按需取内部字段值
            String ipsumVal = innerObj.getString("ipsum");
            String sitVal = innerObj.getString("sit");
            String consecteturVal = innerObj.getString("consectetur");

            // 此处替换为自身业务逻辑
            System.out.printf("索引%d对象值:%s %s %s%n", i, ipsumVal, sitVal, consecteturVal);
        }
    }
}

注意事项

  • 如果字段可能不存在,可使用optString、optInt等带默认值的方法替代直接get方法,避免抛出异常,示例:innerObj.optString("ipsum", "默认值")
  • 数组元素如果不是JSON对象是其他类型,可对应调用getString(index)、getInt(index)等方法直接取值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 23:45:02