在Java中读取JSON数组通常有以下几种方法:
1. 使用Gson库:
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
public class JsonArrayExample {
public static void main(String[] args) {
String json = "[{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 30}]";
JsonArray jsonArray = new JsonParser().parse(json).getAsJsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
String name = jsonObject.get("name").getAsString();
int age = jsonObject.get("age").getAsInt();
System.out.println("Name: " + name + ", Age: " + age);
}
}
}
2. 使用org.json库:
import org.json.JSONArray;
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonStr = "[{\"name\": \"John\", \"age\": 30, \"city\": \"New York\"}, {\"name\": \"Alice\", \"age\": 25, \"city\": \"London\"}]";
JSONArray jsonArray = new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject json = jsonArray.getJSONObject(i);
String name = json.getString("name");
int age = json.getInt("age");
String city = json.getString("city");
System.out.println("Name: " + name + ", Age: " + age + ", City: " + city);
}
}
}
3. 使用Jackson库(需要添加相应的依赖):
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonArrayExample {
public static void main(String[] args) {
String json = "[{\"name\": \"Alice\", \"age\": 25}, {\"name\": \"Bob\", \"age\": 30}]";
ObjectMapper mapper = new ObjectMapper();
try {
JsonNode jsonArray = mapper.readTree(json);
for (JsonNode node : jsonArray) {
String name = node.get("name").asText();
int age = node.get("age").asInt();
System.out.println("Name: " + name + ", Age: " + age);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}