java 中从 json 数组获取值可通过以下方法:使用 gson 库:将 json 字符串解析为 json 数组,然后遍历数组获取值。使用 org.json 库:创建 json 数组,获取数组长度,然后遍历数组获取值。使用 jackson 库:将 json 字符串解析为数组,然后遍历数组获取值。

Java 中 JSON 数组取值
Java 中可以通过以下方法从 JSON 数组中获取值:
1. 使用 GSON 库
使用 GSON 库是获取 JSON 数组值最简单的方法之一。
立即学习“”;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonArray;
// JSON 字符串
String jsonString = "[1, 2, 3]";
// 创建 GSON 对象
Gson gson = new Gson();
// 解析 JSON 字符串
JsonElement jsonElement = gson.fromJson(jsonString, JsonElement.class);
// 检查是否为数组
if (jsonElement.isJsonArray()) {
// 转换为 JSON 数组
JsonArray jsonArray = jsonElement.getAsJsonArray();
// 遍历数组并获取值
for (JsonElement element : jsonArray) {
System.out.println(element.getAsInt()); // 1, 2, 3
}
}
登录后复制
2. 使用 org.json 库
org.json 库提供了另一种获取 JSON 数组值的方法。
import org.json.JSONArray;
import org.json.JSONObject;
// JSON 字符串
String jsonString = "[1, 2, 3]";
// 创建 JSON 数组
JSONArray jsonArray = new JSONArray(jsonString);
// 获取数组长度
int length = jsonArray.length();
// 遍历数组并获取值
for (int i = 0; i < length; i++) {
System.out.println(jsonArray.getInt(i)); // 1, 2, 3
}
登录后复制
3. 使用 Jackson 库
Jackson 库也允许从 JSON 数组中获取值。
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
// JSON 字符串
String jsonString = "[1, 2, 3]";
// 创建 ObjectMapper 对象
ObjectMapper mapper = new ObjectMapper();
// 转换为数组
int[] array = mapper.readValue(jsonString, int[].class);
// 遍历数组并获取值
for (int element : array) {
System.out.println(element); // 1, 2, 3
}
登录后复制
以上就是java 怎么取值的详细内容,更多请关注IDCBABY其它相关文章!
