使用 Java 流解析 JsonArray 结果

Parse the JsonArray result using Java stream

我正在尝试从 JsonArray 获取键的值。结果,我得到了以下格式的 JsonObject

{
  "docs": [
    {
      "_index": "esindex",
      "_type": "esmessage",
      "_id": "4",
      "_version": 1,
      "found": true,
      "_source": {
        "account_number": 4,
        "balance": 27658
      }
    }
  ]
}

我需要找到具有 "found": true 的所有这些文档的 id。生成的JsonArray格式为

[
  {
    "_index": "esindex",
    "_type": "esmessage",
    "_id": "4",
    "_version": 1,
    "found": true,
    "_source": {
      "account_number": 4,
      "balance": 27658
    }
  }
]

我可以使用以下 java 代码获取所有 ID 的列表

 List<Integer> documents = new ArrayList<>();
JsonObject result = esClient.execute(builder.build()).getJsonObject();
        JsonArray jsonArray = result.getAsJsonObject().get("docs").getAsJsonArray();
        while (i < request.getIds().size()) {
            JsonPrimitive checkIfExists = jsonArray.get(i).getAsJsonObject().getAsJsonPrimitive("found");
            if (checkIfExists.getAsString().equals("true"))
                documents.add(result.getAsJsonObject().get("docs").getAsJsonArray().get(i).getAsJsonObject().getAsJsonPrimitive("_id").getAsInt());
            i++;
        }

任何人都可以帮助我,使用 Java 流解析 JsonArray 结果 API

意识到 JsonArray 是一个 Iterable<JsonElement>

意识到这一点后,您搜索并找到“How to convert an iterator to a stream?", where you learn that you can use Spliterators.spliteratorUnknownSize() and StreamSupport.stream() 来执行此操作。

Stream<JsonElement> stream = StreamSupport.stream(
          Spliterators.spliteratorUnknownSize(jsonArray.iterator(),
                                              Spliterator.ORDERED),
          /*parallel*/false);

List<Integer> documents = stream.map(JsonElement::getAsJsonObject)
    .filter(o -> o.getAsJsonPrimitive("found").getAsBoolean())
    .map(o -> o.getAsJsonPrimitive("_id").getAsInt())
    .collect(Collectors.toList());

你当然知道数组的大小,所以你会调用 Spliterators.spliterator(),你当然可以将它们链接在一起:

List<Integer> documents = StreamSupport.stream(
          Spliterators.spliterator(jsonArray.iterator(),
                                   jsonArray.size(),
                                   Spliterator.ORDERED),
          /*parallel*/false)
    .map(JsonElement::getAsJsonObject)
    .filter(o -> o.getAsJsonPrimitive("found").getAsBoolean())
    .map(o -> o.getAsJsonPrimitive("_id").getAsInt())
    .collect(Collectors.toList());