在Java中读取JSON数组通常有以下几种方法:
1. 使用Gson库:
java
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库:
java
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库(需要添加相应的依赖):
java
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();
}
}
}
请根据您的需求选择合适的库进行操作。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/46740.html