简体   繁体   English

放心:从响应列表中提取值

[英]Rest Assured: extract value from Response List

I have a List returned as response.我有一个列表作为响应返回。 I need to get one item from list using product.name and tariffPlan.name.我需要使用产品名称和关税计划名称从列表中获取一项。

    [
  {
    "id": 123,
    "product": {
      "id": 1,
      "code": "credit",
      "name": "Credit"
    },
    "tariffPlan": {
      "id": 1,
      "code": "gold",
      "name": "Gold"
    }
  },
  {
    "id": 234,
    "product": {
      "id": 2,
      "code": "debit",
      "name": "Debit"
    },
    "tariffPlan": {
      "id": 1,
      "code": "gold",
      "name": "Gold"
    }
  }
]

I use Java8.我使用Java8。 Here is my method.这是我的方法。 I got List of Card.class elements.我得到了 Card.class 元素列表。 And then I need to get single Item from list with specified "product.name" and "tariffPlan.name".然后我需要从具有指定“product.name”和“tariffPlan.name”的列表中获取单个项目。

public List<Card> getCardId(String productName, String tariffPlanName) {
    return given()
        .param("product.name", productName)
        .param("tariffPlan.name", tariffPlanName)
        .when().get("/").then()
        .extract().jsonPath().getList("", Card.class);
  }

Is it possible to do it with restAssured?是否可以通过 restAssured 来实现? Maybe use .param method like in my example?也许在我的例子中使用 .param 方法? But in my example .param method is ignored.但在我的示例中 .param 方法被忽略。 Thank you for your ideas.谢谢你的想法。

UPD.更新。 My decision is:我的决定是:

 public Card getCard(String productName, String tariffPlanName) {
    List<Card> cardList = given()
        .when().get("/").then()
        .extract().jsonPath().getList("", Card.class);

    return cardList.stream()
        .filter(card -> card.product.name.equals(productName))
        .filter(card -> card.tariffPlan.name.equals(tariffPlanName))
        .findFirst()
        .get();
  }

If you need to get a value from response json list, here's what worked for me:如果您需要从响应 json 列表中获取值,这对我有用:

Json sample:
[
  {
    "first": "one",
    "second": "two",
    "third": "three"
  }
]

Code:

String first =
given
  .contentType(ContentType.JSON)
.when()
  .get("url")
.then()
.extract().response().body().path("[0].first")

Actually, you can but... you need to handle deserialization issue of default mapper becase if you try do the following:实际上,您可以但是...如果您尝试执行以下操作,则需要处理默认映射器的反序列化问题:

.extract().jsonPath().getList("findAll {it.productName == " + productName + "}", Card.class);

You will failing on converting HashMap to your object type.您将无法将 HashMap 转换为您的对象类型。 It happens because of using gpath expression in path provides json without double quotes on keys by default.发生这种情况是因为在 path 中使用 gpath 表达式提供了默认情况下在键上没有双引号的 json。 So you need to prettify it with (you can put it in RestAssured defaults):所以你需要美化它(你可以把它放在RestAssured默认值中):

.extract().jsonPath().using((GsonObjectMapperFactory) (aClass, s) -> new GsonBuilder().setPrettyPrinting().create())

And as result your would be able to cast things like that:结果你将能够投射这样的东西:

.getObject("findAll {it.productName == 'productName'}.find {it.tariffPlanName.contains('tariffPlanName')}", Card.class)

See full example:查看完整示例:

import com.google.gson.GsonBuilder;
import io.restassured.http.ContentType;
import io.restassured.mapper.factory.GsonObjectMapperFactory;
import lombok.Data;
import org.testng.annotations.Test;

import java.util.HashMap;
import java.util.List;

import static io.restassured.RestAssured.given;

public class TestLogging {

    @Test
    public void apiTest(){
        List<Item> list = given()
                .contentType(ContentType.JSON)
                .when()
                .get("https://jsonplaceholder.typicode.com/posts")
                .then().log().all()
                .extract().jsonPath().using((GsonObjectMapperFactory) (aClass, s) -> new GsonBuilder().setPrettyPrinting().create())
                .getList("findAll {it.userId == 6}.findAll {it.title.contains('sit')}", Item.class);
        list.forEach(System.out::println);
    }

    @Data
    class Item {
        private String userId;
        private String id;
        private String title;
        private String body;
    }
}

Suppose you want to fetch the value of the id, when product name is "Credit" and tariffPlan is "Gold".假设您要获取 id 的值,当产品名称为“Credit”且关税计划为“Gold”时。

Use采用

from(get(url).asString()).getList("findAll { it.product.name == 'Credit' && it.tariffPlan.name == 'Gold'}.id");

Where url - http/https request and get(url).asString() will return a JSON response as string.其中 url - http/https 请求和get(url).asString()将以字符串形式返回 JSON 响应。

Here a kotlin example:这是一个 kotlin 示例:

    @Test
    fun `creat endpoint with invalid payload should return 400 error`() {
        val responseError: List<ErrorClass> = Given {
            spec(requestSpecification)
            body(invalidPayload)
        } When {
            post("/endpoint")
        } Then {
            statusCode(HttpStatus.SC_BAD_REQUEST)
        } Extract {
            body().`as`(object : TypeRef<List<ErrorClass>>() {})
        }

        responseError shouldHaveSize 1
        responseError[0].field shouldBe "xxxx"
        responseError[0].message shouldBe "xxx"
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何验证响应并从 Rest Assured 中的响应正文中提取值? - How to validate a response and extract a value from Response body in Rest Assured? 从 rest 中提取一些字段保证响应 - extract some field from rest assured response 如何使用放心从具有多个命名空间的 SOAP XML 响应中提取价值? - How to extract value from SOAP XML response with multiple namespaces using Rest-assured? 放心。 是否可以从响应 json 中提取 JSONObject/JSONArray? - Rest-assured. Is it possible to extract JSONObject/JSONArray from response json? 如何使用通用代码从 REST Assured 响应中提取 cookie - How to extract cookies from a REST Assured response using common code 如何从嵌套列表中提取项目 - Rest Assured - How to extract item from nested list - Rest Assured 放心。 是否可以从请求 json 中提取值? - Rest-assured. Is it possible to extract value from request json? 如何将访问令牌值从一个 API 响应主体(在一个类中)提取到另一个 API 标头(在另一个类中)在 rest 保证代码中 - How to extract accesss token value from one API response body(in one class) into another API header(in another class) in rest assured code 从 REST-Assured 中的 XML 响应中获取值 - Getting a value from XML response in REST-Assured 使用 GPath 和 Rest Assured 从响应元素获取值 - Getting the value from the response element using GPath and Rest Assured
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM