如何使用 find in 匿名和嵌套数组进行搜索,或者使用 REST-Assured 库在 groovy 的闭包中查找全部?



我有以下 JSON 响应匿名正文,我需要动态解析嵌套数组,以通过使用 groovy 闭包中的findfindAll根据条件检索键的值

[
{
  "children": [
    {
      "attr": {
        "reportId": "1",
        "reportShortName": "ABC",
        "description": "test,
      }
    },
   {
     "attr": {
       "reportId": "2",
       "reportShortName": "XYZ",
       "description": "test",
      }
   }
}
]

我已经尝试了以下方法,但没有运气从 JSON 响应中检索 reportId 键的值

package com.src.test.api;
import static io.restassured.RestAssured.given;
import io.restassured.path.json.JsonPath;
import io.restassured.response.Response;
public class GetReportId {
   public void getReportId(String reportName) throws Exception {
    String searchReports = "http://localhost:8080/reports";
    Response resp=given().request().when().get(searchReports).then().extract().response();
    JsonPath jsonPath = new JsonPath(resp.asString());
    String reportId1 =jsonPath.get("$.find{it.children.contains(restAssuredJsonRootObject.$.children.find{it.attr.reportShortName == 'ABC'})}.attr.reportId");
    String reportId2 = jsonPath.get("$.find{it.children.attr.reportShortName.contains(restAssuredJsonRootObject.$.children.find{it.attr.reportShortName.equals('XYZ')}.attr.reportShortName)}.attr.reportId");
    System.out.println("ReportId: " + reportId1);
  }
}

父匿名数组中可能有多个 JSON 对象,需要在时髦的闭包中使用 find 或 findAll 来获取 reportId

需要得到reportId,但似乎有些不对劲。 任何帮助将不胜感激。

假设你想要所有的reportId

List<String> reportIds = jsonPath.get("children.flatten().attr.reportId");

会给你你想要的,即使父匿名数组有多个条目。

我使用以下 JSON 进行了测试

[
  {
    "children": [
      {
        "attr": {
          "reportId": "1",
          "reportShortName": "ABC",
          "description": "test"
        }
      },
      {
        "attr": {
          "reportId": "2",
          "reportShortName": "XYZ",
          "description": "test"
        }
      }
    ]
  },
  {
    "children": [
      {
        "attr": {
          "reportId": "3",
          "reportShortName": "DEF",
          "description": "test"
        }
      },
      {
        "attr": {
          "reportId": "4",
          "reportShortName": "IJK",
          "description": "test"
        }
      }
    ]
  }
]

它给了我["1", "2", "3", "4"],即所有孩子的 reportId

如果您知道要查找的 reportId 的索引,则可以像这样使用它:

String reportId = jsonPath.get("children.flatten().attr.reportId[0]");

如果您正在寻找特定报告的 reportId,您也可以这样做:

String reportId = jsonPath.get("children.flatten().attr.find{it.reportShortName == 'ABC'}.reportId")

会给你"1".

注: 将结果分配到的变量的类型对于类型推断和强制转换非常重要。例如,您不能执行以下操作:

String [] reportIds = jsonPath.get("children.flatten().attr.reportId");

int reportId = jsonPath.get("children.flatten().attr.reportId[0]");

这两件事都会抛出一个 ClassCastException。

最新更新