在Java中,可以使用Java標(biāo)準(zhǔn)庫中的org.json
包來解析和處理JSON數(shù)據(jù)。以下是如何取出JSON數(shù)組中的值的示例代碼:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
// JSON數(shù)組的示例數(shù)據(jù)
String jsonStr = "[{\"name\":\"John\",\"age\":30,\"city\":\"New York\"},{\"name\":\"Alice\",\"age\":25,\"city\":\"London\"}]";
try {
// 將JSON字符串轉(zhuǎn)換為JSON數(shù)組
JSONArray jsonArray = new JSONArray(jsonStr);
// 遍歷JSON數(shù)組
for (int i = 0; i < jsonArray.length(); i++) {
// 獲取數(shù)組中的JSON對(duì)象
JSONObject json = jsonArray.getJSONObject(i);
// 取出JSON對(duì)象中的值
String name = json.getString("name");
int age = json.getInt("age");
String city = json.getString("city");
// 打印取出的值
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("City: " + city);
System.out.println();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
運(yùn)行以上代碼,會(huì)輸出如下結(jié)果:
Name: John
Age: 30
City: New York
Name: Alice
Age: 25
City: London
注意:在使用org.json
包時(shí),需要將其添加到項(xiàng)目的依賴中。