调用GET API遇JsonPathException:JSON文档解析失败求助
GET接口JSON解析失败问题排查与修复
调用GET接口时抛出JsonPathException,提示"Failed to parse the JSON document",根源为JSON输入为空或无效,结合代码与错误堆栈分析如下:
错误根源定位
从错误堆栈的Caused by: java.lang.IllegalArgumentException: The JSON input text should neither be null nor empty可知,getPlaceResponse为空或非有效JSON字符串,导致JsonPath无法完成解析。
代码问题点排查
- Add Place接口参数错误:代码中
queryParam("Key", "=qaclick123")多了前缀=,正确的Key值应为qaclick123。该错误会导致Add Place接口无法生成有效place_id,后续Update、Get Place接口因无效place_id返回异常响应(甚至空响应)。 - Get Place字段名错误:Get Place接口返回的地址字段为
address,但代码中用js1.getString("newAddress")获取,即使响应正常也会返回null。 - Update Place请求体冗余:请求体中多余的
"key":"qaclick123"字段属于无效内容,建议移除。
修复后的完整代码
import io.restassured.RestAssured; import io.restassured.path.json.JsonPath; import static io.restassured.RestAssured.*; import static org.hamcrest.Matchers.*; import files.payload; public class Basics { public static void main(String[] args) { RestAssured.baseURI= "https://rahulshettyacademy.com" ; // 调用Add Place接口 String response=given().log().all() .queryParam("Key", "qaclick123") // 修正Key参数,移除多余的= .header("Content-Type", "application/json;charset=UTF-8") .body(payload.AddPlace()) .post("maps/api/place/add/json") .then().assertThat().statusCode(200) .body("scope", equalTo("APP")) .header("Server", "Apache/2.4.52 (Ubuntu)") .extract().response().asString(); System.out.println(response); JsonPath js=new JsonPath(response); String placeId=js.getString("place_id"); String addressJsonString = js.getString("address"); System.out.println(placeId); System.out.println("Address:"+addressJsonString); // 更新地址 String newAddress = "Summer Walk, Africa"; given().log().all() .queryParam("Key","qaclick123") .header("Content-Type", "application/json") .body("{\r\n" + "\"place_id\":\""+placeId+"\",\r\n" + "\"address\":\""+newAddress+"\"\r\n" // 移除冗余的key字段 + "}") .when().put("maps/api/place/update/json") .then().assertThat().log().all() .statusCode(200) .body("msg", equalTo("Address successfully updated")); // 获取更新后的地址 String getPlaceResponse= given().log().all() .queryParam("Key", "qaclick123") .queryParam("place_id",placeId) .when().get("maps/api/place/get/json") .then().assertThat().log().all() .statusCode(200) .extract().response().asString(); JsonPath js1 = new JsonPath(getPlaceResponse); String actualAddress = js1.getString("address"); // 修正字段名为address System.out.println("更新后的地址:"+actualAddress); } }
验证要点
- 运行修复后代码,确认Add Place接口返回有效
place_id; - 确认Update Place接口返回
Address successfully updated; - 确认Get Place接口返回正确JSON,并正常打印更新后的地址。
内容的提问来源于stack exchange,提问作者Vikas Bhat
相关产品推荐
相关产品推荐

