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
相关产品推荐
相关产品推荐

