如何在java 8中获取其他json元素的值

我有一个字符串 jsonArrayStr 的 JSON

[
  {
    "Debtoraccount": "1716429833","Creditoraccount": "NL97RABO5372111783","Amount": 2.6,"EndBalance": 1367.99,"TransactionTime": "27-Jun-2018 04:04 PM","Label": "Rent"
  },{
    "Debtoraccount": "1792432233","Creditoraccount": "NL27RABO4067005407","Amount": 199.37,"EndBalance": 271.72,"TransactionTime": "07-Jul-2013 03:40 AM","Label": "Internet"
  },{
    "Debtoraccount": "0417164298","Amount": 2.2,"Label": "Rent"
  }
]

我想得到一个包含 Debtoraccount = NL95RABO0417164298 和 Label = Rent 的所有金额的列表。

我尝试了以下代码来获取 Debtoraccount = NL95RABO0417164298 的所有值,但是我无法获取金额值。

JSONArray jsonArray = new JSONArray(jsonArrayStr);
IntStream.range(0,jsonArray.length())
  .mapToObj(index -> ((JSONObject)jsonArray.get(index)).optString("Debtoraccount")).filter(p -> p.equals("NL95RABO0417164298"))
  .collect(Collectors.toList());

请帮帮我,我错过了什么?

likedong13131313 回答:如何在java 8中获取其他json元素的值

正如评论中所指出的,这可以使用 filter() 来实现。

以下代码片段过滤掉所有具有 DebtorAccount = NL95RABO0417164298 和 Label = Rent 的 JSONObject(s),并将结果存储在 filteredJSONArray 中。

JSONArray jsonArray = new JSONArray(jsonArrayStr);
JSONArray filteredJSONArray = new JSONArray();

IntStream
        .range(0,jsonArray.length())
        .filter(index -> jsonArray.getJSONObject(index).get("DebtorAccount").equals("NL95RABO0417164298") && jsonArray.getJSONObject(index).get("Label").equals("Rent"))
        .forEach(index -> filteredJSONArray.put(jsonArray.get(index)));

System.out.println(filteredJSONArray.toString());
本文链接:https://www.f2er.com/6617.html

大家都在问