【问题标题】:Filtering on nested JSON array: Rest Assured过滤嵌套的 JSON 数组:放心
【发布时间】:2021-08-03 06:52:24
【问题描述】:

我正在尝试根据嵌套 JSON 数组中的值过滤我的 GET 响应 (JSON)。例如:在下面的 JSON 中,我想过滤一个 JSON 数组并使用 Chocolate 作为面糊打印蛋糕的名称。

{
"id": "0001",
"type": "donut",
"name": "Choco Blueberry Cake",
"ppu": 0.55,
"batter":[
         { "id": "1001", "type": "Regular" },
         { "id": "1002", "type": "Chocolate" },
         { "id": "1003", "type": "Blueberry" }
 ]
}

我尝试过类似的方法:

List<String> chocolateCakeList =jsonPath.getList("findAll{it.batter.type=='chocolate'}.name");

List<String> chocolateCakeList =jsonPath.getList("findAll{it.batter.it.type=='chocolate'}.name");

两者都返回空列表。

【问题讨论】:

    标签: json rest-assured rest-assured-jsonpath


    【解决方案1】:

    问题

    1. 首先,如果您想使用findAll,那么要提取的对象必须是一个数组。您的 json 是对象 {},而不是数组 []。实际上,您的嵌套对象batter 是一个数组[]。

    2. 要搜索的关键字是Chocolate,而不是chocolate。此处应用区分大小写。

    解决方案

    -如果您的整个回复正是您发布的内容,那么提取路径是

    String name = jsonPath.getString("name")
    

    -如果您的回复具有这样的结构。

    [
      {
        "id": "0001",
        "type": "donut",
        "name": "Choco Blueberry Cake",
        "ppu": 0.55,
        "batter": [
          {
            "id": "1001",
            "type": "Regular"
          },
          {
            "id": "1002",
            "type": "Chocolate"
          },
          {
            "id": "1003",
            "type": "Blueberry"
          }
        ]
      },
      {
        "id": "0002",
        "type": "donut",
        "name": "Choco Blueberry Cake",
        "ppu": 0.55,
        "batter": [
          {
            "id": "1001",
            "type": "Regular"
          },
          {
            "id": "1002",
            "type": "Chocolate 2"
          },
          {
            "id": "1003",
            "type": "Blueberry"
          }
        ]
      }
    ]
    

    那么提取就是

    List<String> list = jsonPath.getList("findAll {it.batter.findAll {it.type == 'Chocolate'}}.name");
    

    【讨论】:

    • 非常感谢。我的回应也是一个数组。这个解决方案奏效了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-05
    • 2015-02-17
    • 2020-08-25
    • 2012-08-07
    • 1970-01-01
    相关资源
    最近更新 更多