如何使用 restassured 从 json 中获取价值

How to get value from json using restassured

我有 json 并且有 'products' 的数组。

{
  "data": [
    {
      "contact_id": "...",
      "email": "...",
      "first_name": "...",
      "hash_campaign": "",
      "hash_campaign_valid_to_date": null,
      "hash_password": "",
      "last_name": "...",
      "loans": [
        
      ],
      "max_available_loan_amount": 2000.00,
      "middle_name": "P",
      "mobile": "...",
      "personal_id": "...",
      "product_code": 2,
      "products": [
        {
          "available_loan_terms": [
            15,
            21,
            30,
            7,
            45
          ],
          "default_amount": 0,
          "default_term": 15,
          "document_required": 0,
          "max_available_loan_amount": 2000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 0.00,
          "product_code": 2
        },
        {
          "available_loan_terms": [
            3,
            6,
            4,
            5
          ],
          "default_amount": 0,
          "default_term": 0,
          "document_required": 0,
          "max_available_loan_amount": 4000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 1300.00,
          "product_code": 101
        },
        {
          "available_loan_terms": [
            3,
            6,
            4,
            5
          ],
          "default_amount": 0,
          "default_term": 0,
          "document_required": 0,
          "max_available_loan_amount": 3000.00,
          "max_loan_amount": 0,
          "max_monthly_payment": 1510.00,
          "product_code": 100
        }
      ],
      "scoring_through_zoral": "0"
    }
  ],
  "description": "...",
  "requestId": "...",
  "status": 8888
}

我只想获取代码为 2 的产品的字段 'default_term' 和 'max_available_loan_amount' 的值。 我用的放心 我试过了

 List<List> lists = response.body().jsonPath().getList("data.products");

但是此代码 returns 列表只有一项,我的意思是一项中的所有产品... 如何从此 json 获取产品数组中第一项的信息???

第 1 步:创建 POJO 到映射

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class Product {
    @JsonProperty("default_term")
    private int default_term;
    @JsonProperty("max_available_loan_amount")
    private double max_available_loan_amount;
}

第 2 步:提取响应并反序列化为对象。

Product product = ...jsonPath().getObject("data[0].products.find {it.product_code == 2}", Product.class);
System.out.println(product);
//Product(default_term=15, max_available_loan_amount=2000.0)

这可行

List<Integer> li_defaultTerm = response.getBody().jsonPath().get("$..products[?(@.product_code=='2')].default_term");
System.out.println(li_defaultTerm.get(0));
//15

List<Double> li_MaxAvailLoanAmount = response.getBody().jsonPath().get("$..products[?(@.product_code=='2')].max_available_loan_amount");
System.out.println(li_MaxAvailLoanAmount.get(0));
//2000.0