我有一个列表作为响应返回。我需要使用 product.name 和 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"
}
}
]
我使用 Java8。这是我的方法。我得到了 Card.class 元素列表。然后我需要从具有指定“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);
}
是否可以使用 restAssured 来做到这一点?也许像我的例子一样使用 .param 方法?但在我的示例中,.param 方法被忽略了。谢谢你的想法。
更新。我的决定是:
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();
}
最佳答案
如果您需要从响应 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")
关于java - 放心 : extract value from Response List,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45416987/