无法流式传输JSON数组 [英] Unable to stream JSON array
问题描述
以下是我的代码:
导入的是:org.json.JSONArray,org.json.JSONObject
Imports are: org.json.JSONArray, org.json.JSONObject
String x="{\"count\":25,\"rows\":[{\"id\":10,\"name\":\"xxx\"},{\"id\":11,\"name\":\"xyx\"}]}";
JSONObject obj=new JSONObject(x);
JSONArray arr=obj.getJSONArray("rows");
实际数据中有许多记录,其中包含许多我需要过滤的键值.所以我尝试了arr.stream()
,但是在编译本身上,它显示了方法stream()
对于类型JSONArray
是未定义的.
Actual data has many records with many key values which i need to filter. So i tried arr.stream()
but on compilation itself it shows method stream()
is undefined for type JSONArray
.
我使用Java8.流用于列表.我在arr中获取键行的值.请说明为什么以及如何解决.
I use java 8. streams work for list. I am getting values of key rows in arr. Please clarify why and how it can be solved.
推荐答案
org.json.JSONArray
基本上不是数组.这只是一个表示JSON数组的类(是的,听起来很奇怪),它是[]
.
Well basically org.json.JSONArray
is not array as such. It's just a class that represents JSON array (yep, sounds weird) which is []
.
好消息是它实现了Iterable
.这样您就可以获得这样的流:
Good news is that it implements Iterable
. So you can get a stream like that:
String x="{\"count\":25,\"rows\":[{\"id\":10,\"name\":\"xxx\"},
{\"id\":11,\"name\":\"xyx\"}]}";
JSONObject obj = new JSONObject(x);
JSONArray arr= obj.getJSONArray("rows");
StreamSupport.stream(arr.spliterator(), false)
.forEach(System.out::println);
出局:
{"name":"xxx","id":10}
{"name":"xyx","id":11}
编辑1-评论的答案
您提供的代码对我来说非常合适.它会过滤掉数组中除具有id==11
的对象之外的所有对象:
Code that you provided works perfectly fine for me. It does filter all objects in array except those which have id==11
:
List<JSONObject> list = StreamSupport.stream(arr.spliterator(), false)
.map(val -> (JSONObject) val)
.filter(val -> val.getInt("id") == 11)
.collect(Collectors.toList());
System.out.println(list);
出局:
[{"name":"xyx","id":11}]
这篇关于无法流式传输JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!