要遍历 JSON 数组 Java,可以使用以下方法:forEach 循环for 循环和 get 方法迭代器流 API

遍历 JSON 数组 Java
如何遍历 JSON 数组 Java?
要遍历 JSON 数组 Java,可以使用以下方法之一:
使用 forEach 循环
立即学习“Java免费学习笔记(深入)”;
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
<code class="java">JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");
jsonArray.forEach(element -> System.out.println(element));</code>使用 for 循环和 get 方法
<code class="java">JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");
for (int i = 0; i < jsonArray.length(); i++) {
System.out.println(jsonArray.get(i));
}</code>使用迭代器
<code class="java">JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");
Iterator<Object> iterator = jsonArray.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}</code>使用流 API
<code class="java">JSONArray jsonArray = new JSONArray("[1, 2, 3, 4, 5]");
jsonArray.stream().forEach(System.out::println);</code>说明:
JSONArray 是用于表示 JSON 数组的 Java 类。forEach 循环是 Java 8 中引入的,它遍历数组中的每个元素并执行指定的动作。get 方法用于获取数组中指定索引处的元素。以上就是怎么遍历json数组java的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号