共計 884 個字符,預計需要花費 3 分鐘才能閱讀完成。
在 Java 中,可以使用 org.json 庫來處理 JSON 數據。下面是一個簡單的示例,演示了如何遍歷 JSONArray 并獲取其中的數據:
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {public static void main(String[] args) {
// 示例 JSON 數據
String jsonStr = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"}, {\"name\":\"Jane\",\"age\":25,\"city\":\"Paris\"}]";
// 將 JSON 字符串解析為 JSONArray
JSONArray jsonArray = new JSONArray(jsonStr);
// 遍歷 JSONArray
for (int i = 0; i < jsonArray.length(); i++) {
// 獲取當前索引處的 JSONObject
JSONObject jsonObj = jsonArray.getJSONObject(i);
// 從 JSONObject 中獲取數據
String name = jsonObj.getString("name");
int age = jsonObj.getInt("age");
String city = jsonObj.getString("city");
// 打印數據
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println();}
}
}
在上述示例中,首先將 JSON 字符串解析為 JSONArray 對象。然后,使用 getJSONObject() 方法獲取每個索引處的 JSONObject,并使用getString() 和getInt()等方法從 JSONObject 中獲取數據。最后,可以根據需要對獲取的數據進行處理,例如打印出來。
丸趣 TV 網 – 提供最優質的資源集合!
正文完