根据条件从REST Json响应中检索特定数据



我查看了所有相关的帖子,但找不到我要找的内容。使用验证了查询语法https://codebeautify.org/jsonpath-tester和https://jsonpath.com/.在下面的代码中,如果我只打印id,我会得到正确的响应。我正在寻找标题,基于特定的用户id和id。

得到"无效的JSON表达式";作为o/p。有人能帮忙吗!

public void restPost2(){
RestAssured.baseURI = "https://jsonplaceholder.typicode.com/posts";
RequestSpecification req = RestAssured.given().log().all();
String res1 = req.given().when().get().then().extract().asString();
JsonPath js = new JsonPath(res1);
System.out.println("list of Ids : " + js.get("id"));
System.out.println("specific title : " + js.get("(?(@.userId == '3') && (@.id == '23')).title"));
}

以下更改将解决您的问题。

  • 使用JsonPath.read将json字符串设置为查询

  • jsonPath查询的语法需要更正。

建议您再次参考jsonPath文档。

请查找的工作示例

json = <data fetched for the api>
Object x = JsonPath.read(json,"$..id");
Object y = JsonPath.read(json,"$[?(@.userId == 3 && @.id == 23)]");

最新更新