问题描述
我查看了所有相关帖子,但找不到所需的内容。 使用https://codebeautify.org/jsonpath-tester和https://jsonpath.com/验证了查询语法。在下面的代码中,如果我仅打印id,我将得到正确的响应。我正在根据特定的用户ID和ID寻找标题。
以o / p获取“无效的JSON表达式”。任何人都可以在这里提供帮助!
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查询的语法需要更正。
suggest you to refer jsonPath documentation again.
请找到一个有效的示例
json = <data fetched for the api>
Object x = JsonPath.read(json,"$..id");
Object y = JsonPath.read(json,"$[?(@.userId == 3 && @.id == 23)]");