java json数组怎么取值

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

java 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怎么循环数组
下一篇: java数组怎么转list

作者:admin @ 24资源网   2024-11-27

本站所有软件、源码、文章均有网友提供,如有侵权联系308410122@qq.com

与本文相关文章

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。