Java 中从 JSON 数组获取值可通过以下方法:使用 GSON 库:将 JSON 字符串解析为 JSON 数组,然后遍历数组获取值。使用 org.json 库:创建 JSON 数组,获取数组长度,然后遍历数组获取值。使用 Jackson 库:将 JSON 字符串解析为数组,然后遍历数组获取值。
Java 中 JSON 数组取值
Java 中可以通过以下方法从 JSON 数组中获取值:
1. 使用 GSON 库
使用 GSON 库是获取 JSON 数组值最简单的方法之一。
立即学习“Java免费学习笔记(深入)”;
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 json数组怎么取值的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号