((JSONArray) JsonUtils.parseStringToJsonObject(response.getResponseBody()).get("firstArray")).stream()
.map(s->((JSONArray) s).get(1).toString()).collect(Collectors.toList())
为什么这段代码会返回一个对象而不是列表?
(响应类型为 IHttpResponse<String>
)
最佳答案
下面的代码应该可以工作
初始化 JSONArray 的示例代码
JSONArray jsonArray =new JSONArray();
JSONObject j1 = new JSONObject();
j1.put ("key", "Stack");
JSONObject j2 = new JSONObject();
j2.put ("key", "Overflow");
jsonArray.add(j1);
jsonArray.add(j2);
将 JSONArray 转换为列表。您的代码中有几个问题。第一个是,您在映射函数中使用 JSONArray ,它应该是 JSONObject 。第二个是,map返回Stream,我们需要将其类型转换为Stream<String>
List<String> output = arrayToStream(jsonArray)
.map(JSONObject.class::cast)
.map(s -> s.get("key").toString())
.collect(Collectors.toList());
将 JSONArray 转换为 Stream<Object>
的 Util 方法
private static Stream<Object> arrayToStream(JSONArray array) {
return StreamSupport.stream(array.spliterator(), false);
}
关于Java流无法识别类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48811780/