Java 中解析 JSON 字符串数组的方法有:使用内置的 JSONArray 类,如 JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");。使用第三方库,如 Jackson 或 Gson,如 int[] array = mapper.readValue("[1, 2, 3, 4, 5]", int[].class);。

Java 中如何解析 JSON 字符串数组?
使用内置方法
Java 提供了 JSONArray 类用于解析 JSON 字符串数组。
<code class="java">import org.json.JSONArray;
JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");</code>使用第三方库
立即学习“Java免费学习笔记(深入)”;
也可以使用第三方库,如 Jackson 或 Gson,来解析 JSON 字符串数组。
Jackson
<code class="java">import com.fasterxml.jackson.databind.ObjectMapper;
ObjectMapper mapper = new ObjectMapper();
int[] array = mapper.readValue("[1, 2, 3, 4, 5]", int[].class);</code>Gson
<code class="java">import com.google.gson.Gson;
Gson gson = new Gson();
int[] array = gson.fromJson("[1, 2, 3, 4, 5]", int[].class);</code>步骤
解析 JSON 字符串数组的步骤如下:
- 创建一个
JSONArray对象或第三方库的类。 - 解析 JSON 字符串。
- 从
JSONArray中提取数组元素。
示例
以下代码示例演示如何解析 JSON 字符串数组并获取其元素:
<code class="java">JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");
for (int i = 0; i < jsonArray.length(); i++) {
int number = (int) jsonArray.get(i);
System.out.println(number);
}</code>输出
<code>1 2 3 4 5</code>











