在JSON数组中从JSONObject中获取值的方法是通过使用JSONObject的get方法来获取指定键的值。首先,我们需要将JSON数组解析为JSONArray对象,然后遍历数组中的每个JSONObject,使用get方法获取指定键的值。
以下是一个示例代码,演示如何在JSON数组中从JSONObject中获取值:
import org.json.JSONArray;
import org.json.JSONObject;
public class JSONExample {
public static void main(String[] args) {
// 示例 JSON 字符串
String jsonString = "[{\"name\":\"John\", \"age\":30, \"city\":\"New York\"}, " +
"{\"name\":\"Alice\", \"age\":25, \"city\":\"London\"}]";
try {
// 解析 JSON 字符串为 JSONArray
JSONArray jsonArray = new JSONArray(jsonString);
// 遍历 JSONArray 中的每个 JSONObject
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
// 从 JSONObject 中获取指定键的值
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
String city = jsonObject.getString("city");
// 打印获取到的值
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
上述代码中,我们首先将示例的JSON字符串解析为JSONArray对象。然后,使用for循环遍历JSONArray中的每个JSONObject。在每个JSONObject中,我们使用getString、getInt等方法来获取指定键的值,并将其打印出来。
领取专属 10元无门槛券
手把手带您无忧上云