Java使用org.json库如何获取JSON数组内无名称JSON对象的值
org.json 解析顶层对象内部数组元素的方案
你可以直接按以下步骤操作:
- 先将API返回的JSON字符串解析为
JSONObject顶层对象 - 通过顶层对象的
getJSONArray()方法,传入数组对应的keylorem拿到目标数组 - 遍历数组的每个索引,调用
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
相关产品推荐
相关产品推荐

