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]");
使用第三方库
立即学习“Java免费学习笔记(深入)”;
也可以使用第三方库,如 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 字符串数组的步骤如下:
示例
以下代码示例演示如何解析 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
以上就是java怎么json解析字符串数组的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号