gson 使用Java流解析JsonArray结果

7vux5j2d  于 2022-11-06  发布在  Java
关注(0)|答案(1)|浏览(225)

我尝试从JsonArray中获取键的值。

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

我需要找到所有具有"found": true的文档的id

[
  {
    "_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流API解析JsonArray结果吗

piwo6bdm

piwo6bdm1#

要知道JsonArray是一个Iterable<JsonElement>
有了这种认识,您搜索并找到了“How to convert an iterator to a stream?“,在那里您了解到可以使用Spliterators.spliteratorUnknownSize()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());

相关问题