【问题标题】:extract value from json array of API response without brackets not working从没有括号的API响应的json数组中提取值不起作用
【发布时间】:2018-03-16 10:26:00
【问题描述】:

这里是 JSON:

{
"first":0,
"rows":100,
"data":[
{
"id":326,
"tag":"QATA9",
"workNo":"qat12345"
}
],
"totalRecords":1
}

我的代码是:

JsonPath jsonPathEvaluator = response.jsonPath();
wID = jsonPathEvaluator.get("data.id");
System.out.println("id is "+ wID);

String responseBody = response.getBody().asString();
int statusCode = response.getStatusCode();

在输出中显示 [326] 但我只需要 326 的值

【问题讨论】:

    标签: java json rest-assured web-api-testing rest-assured-jsonpath


    【解决方案1】:

    [] 分隔数组,因此库将其视为数组。只需选择第一个元素,就可以了。

    试试这个:

    JsonPath jsonPathEvaluator = response.jsonPath();
    wID = jsonPathEvaluator.get("data.id")[0];
    System.out.println("id is "+ wID);
    

    然后,您还应该记住,首先使用数组这一事实可能表明您可能有多个元素;在这种情况下,您应该简单地遍历数组。

    【讨论】:

      【解决方案2】:

      试试这个

       JsonPath jsonPathEvaluator = response.jsonPath();
      wID = jsonPathEvaluator.get("data[0].id");
      System.out.println("id is "+ wID);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-09-23
        • 2018-09-14
        • 1970-01-01
        • 2017-01-21
        • 2019-04-17
        • 1970-01-01
        • 2021-12-22
        • 1970-01-01
        相关资源
        最近更新 更多