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

Java如何从JSON数组中提取指定父键下子键及editableField值

问题根因

你出现报错的核心原因是取值方法调用错误:

  • "Header - Goods Receipt"对应的节点是JSONArray类型,但你用了optString()方法将其强制转换为了String类型
  • String类本身没有keys()、getJSONObject()方法,因此编译器会报找不到对应方法的错误

修正后的完整代码

假设你使用的是org.json官方JSON库,修正后代码如下:

for (int i = 0; i < fieldsArray.length(); i++) {
    JSONObject fieldsObject = fieldsArray.optJSONObject(i);
    if (fieldsObject == null) {
        continue;
    }
    Iterator<String> iterator = fieldsObject.keys();
    while (iterator.hasNext()) {
        String currentParentKey = iterator.next();
        // 只处理目标Header节点,不需要可以删掉这个判断
        if (!"Header - Goods Receipt".equals(currentParentKey)) {
            continue;
        }
        // 这里用optJSONArray取数组类型的值,不要转成String
        JSONArray currentParentValue = fieldsObject.optJSONArray(currentParentKey);
        if (currentParentValue == null) {
            continue;
        }
        // 先遍历数组里的每一个字段对象
        for (int j = 0; j < currentParentValue.length(); j++) {
            JSONObject item = currentParentValue.optJSONObject(j);
            if (item == null) {
                continue;
            }
            Iterator<String> childKeyIterator = item.keys();
            while (childKeyIterator.hasNext()) {
                String fieldName = childKeyIterator.next();
                JSONObject fieldProps = item.optJSONObject(fieldName);
                if (fieldProps != null) {
                    String isEditable = fieldProps.optString("editableField");
                    // 这里可以自行处理拿到的字段名和可编辑属性,比如打印:
                    System.out.println("字段:" + fieldName + ",是否可编辑:" + isEditable);
                }
            }
        }
    }
}

额外说明

  • 代码里添加了空值判断,避免节点不存在时出现空指针异常
  • 如果你的JSON库不是org.json,只需要对应替换JSONArray、JSONObject的相关取值方法即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 15:36:03