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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45416987/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 08:41:18  来源:igfitidea点击:

Rest Assured: extract value from Response List

javarest-assured

提问by Антон

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. Here is my method. I got List of Card.class elements. And then I need to get single Item from list with specified "product.name" and "tariffPlan.name".

我使用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);
  }

Is it possible to do it with restAssured? Maybe use .param method like in my example? But in my example .param method is ignored. Thank you for your ideas.

是否可以通过 restAssured 来实现?也许在我的例子中使用 .param 方法?但在我的例子中 .param 方法被忽略了。谢谢你的想法。

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();
  }

回答by Sofia Temnyk

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")

回答by Himanshu Dhamija

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 响应。

回答by RocketRaccoon

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. It happens because of using gpath expression in path provides json without double quotes on keys by default. So you need to prettify it with (you can put it in RestAssureddefaults):

您将无法将 HashMap 转换为您的对象类型。发生这种情况是因为在 path 中使用 gpath 表达式提供了默认情况下在键上没有双引号的 json。所以你需要美化它(你可以把它放在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;
    }
}