使用 Jackson JSON 库中的 JsonMapper 类可以将 JSON 数组转换为Java数组,步骤如下:1. 导入 Jackson 库;2. 创建 ObjectMapper;3. 将 JSON 数组解析为字符串;4. 使用 ObjectMapper 将 JSON 数组转换为 Java 数组。
JSON 数组转 Java
简短回答:
使用 Jackson JSON 库中的 JsonMapper 类可以将 JSON 数组转换为 Java 数组。
详细说明:
-
导入 Jackson 库:
import com.fasterxml.jackson.databind
.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException;
-
创建 ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
-
将 JSON 数组解析为字符串:
String json = "[1,2,3,4,5]";
-
使用 ObjectMapper 将 JSON 数组转换为 Java 数组:
int[] intArray = mapper.readValue(json, int[].class);
代码示例:
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class JsonArrayToJava {
public static void main(String[] args) throws JsonProcessingException {
// 创建 ObjectMapper
ObjectMapper mapper = new ObjectMapper();
// JSON 数组
String json = "[1,2,3,4,5]";
// 将 JSON 数组转换为 Java 数组
int[] intArray = mapper.readValue(json, int[].class);
// 打印 Java 数组
for (int num : intArray) {
System.out.println(num);
}
}
}输出:
1 2 3 4 5









