首页 > 解决方案 > 使用 Rest Assured 验证 Json 对象中的值

问题描述

我想验证 id: 1 属于 Tiger Nixon

{"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""}

我一直在关注这个文档:https://github.com/rest-assured/rest-assured/wiki/Usage#json-using-jsonpath ,这个部分body("shopping.category.find { it.@type == 'groceries' }.item", hasItems("Chocolate", "Coffee"));

目前我得到一个空指针异常。我可以使用一些帮助来提出解决方案。在此先感谢您的时间。

import com.google.gson.JsonObject;
import io.restassured.RestAssured;
import org.testng.Assert;

public class RestAssuredExample_2 {

    public void getResponse() {
        JsonObject responseObject = RestAssured.get("http://dummy.restapiexample.com/api/v1/employees")
                .then()
                .extract().response().as(JsonObject.class);

        String emp1Name = responseObject.get("data.find{it.@id=='1'}.employee_name").toString();
        Assert.assertEquals(emp1Name, "Tiger Nixon");
    }

    public static void main(String[] args) {
        RestAssuredExample_2 rest2 = new RestAssuredExample_2();
        rest2.getResponse();
    }
}  

错误:

Exception in thread "main" java.lang.NullPointerException
    at HTTPz.RestAssuredExample_2.getResponse(RestAssuredExample_2.java:16)

标签: javajsonrest-assured

解决方案


试图复制这种情况

String responseObject = RestAssured.get("http://dummy.restapiexample.com/api/v1/employees").then().extract().asString();
JsonPath js = new JsonPath(responseObject);
String emp1Name = js.get("data.find {it.id =='1'}.employee_name").toString();
System.out.println(emp1Name);

我将emp1Name的值设为“ Tiger Nixon

不同之处 :

原来的 : it.@id=='1'

矿 : it.id =='1'

似乎@ 是用于 XMLPath 而不是 JSONPath,老实说,我也不会详细了解它,因为我只使用 JSONPath 很长时间了 :)


推荐阅读