在Java中遍历嵌套的JSON数组,你可以使用org.json库。以下是一个示例代码,展示了如何遍历嵌套的JSON数组:
import org.json.JSONArray;import org.json.JSONObject;public class JsonArrayTraversal {public static void main(String[] args) {// 假设这是你的JSON数据String jsonStr = "{\"data\":[{\"name\":\"Alice\",\"age\":20},{\"name\":\"Bob\",\"age\":25}],\"other\":[{\"name\":\"Charlie\",\"age\":30}]}";try {// 将JSON字符串转换为JSONObjectJSONObject jsonObject = new JSONObject(jsonStr);// 获取名为"data"的JSONArrayJSONArray dataArray = jsonObject.getJSONArray("data");// 遍历"data"数组for (int i = 0; i < dataArray.length(); i++) {JSONObject dataObject = dataArray.getJSONObject(i);// 获取"name"和"age"字段String name = dataObject.getString("name");int age = dataObject.getInt("age");System.out.println("Name: " + name + ", Age: " + age);// 如果"data"对象中还有嵌套的数组,可以继续遍历if (dataObject.has("other")) {JSONArray otherArray = dataObject.getJSONArray("other");for (int j = 0; j < otherArray.length(); j++) {JSONObject otherObject = otherArray.getJSONObject(j);String otherName = otherObject.getString("name");int otherAge = otherObject.getInt("age");System.out.println("Other Name: " + otherName + ", Other Age: " + otherAge);}}}} catch (JSONException e) {e.printStackTrace();}}}
这个示例代码首先将JSON字符串转换为JSONObject,然后从中获取名为"data"的JSONArray。接着,它遍历"data"数组中的每个元素,并从中提取"name"和"age"字段。如果"data"对象中包含嵌套的数组(例如"other"),代码还会遍历这个嵌套数组。
请注意,你需要将org.json库添加到你的项目中,以便使用上述代码。如果你使用的是Maven,可以在pom.xml文件中添加以下依赖:
org.json json
如果你使用的是其他构建工具或手动管理依赖,请确保下载并添加org.json库的jar文件到你的项目中

