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 字符串数组。
import org.json.JSONArray;
JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");使用第三方库
也可以使用第三方库,如 Jackson 或 Gson,来解析 JSON 字符串数组。
Jackson
import com.fasterxml.jackson.databind.ObjectMapper; ObjectMapper mapper = new ObjectMapper(); int[] array = mapper.readValue("[1, 2, 3, 4, 5]", int[].class);
Gson
import com.google.gson.Gson;
Gson gson = new Gson();
int[] array = gson.fromJson("[1, 2, 3, 4, 5]", int[].class);步骤
解析 JSON 字符串数组的步骤如下:
JSONArray 对象或第三方库的类。JSONArray 中提取数组元素。示例
以下代码示例演示如何解析 JSON 字符串数组并获取其元素:
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);
}输出
1 2 3 4 5