在Java中获取JSON数组中的值,可以使用org.json库、Jackson库或Gson库。以下是使用org.json库获取JSON数组中值的示例代码:
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\":\"Alice\",\"age\":25,\"city\":\"London\"}]";
try {
// 将JSON字符串转换为JSON数组
JSONArray jsonArray = new JSONArray(jsonStr);
// 遍历JSON数组
for (int i = 0; i < jsonArray.length(); i++) {
// 获取数组中的JSON对象
JSONObject json = jsonArray.getJSONObject(i);
// 取出JSON对象中的值
String name = json.getString("name");
int age = json.getInt("age");
String city = json.getString("city");
System.out.println("Name: " + name + ", Age: " + age + ", City: " + city);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
如果你使用的是其他JSON处理库,如Jackson或Gson,请参考相应的文档进行操作。