如何使用Rest Assured从JSON中提取指定的Model对象
用Java+Rest Assured提取JSON响应中Model字段并转为字符串
我正在编写API测试,需要从接口返回的JSON数据里提取"Model"字段对应的对象,再把它转换成字符串。使用Java语言搭配Rest Assured框架,以下是我的测试代码和接口响应示例JSON:
测试代码
public static String returnCity(String CityId) { String string = ""; Response response = given().spec(returnRequest(token)) .when().get(Configuration.baseUrl + "/api/v1/city/" + CityId) .then() .log().all() .contentType(JSON) .assertThat() .statusCode(200) .extract().response(); string = response.body("Model"); String city = JsonPath.read(string, "$.Model").toString(); return city; }
响应示例JSON
{ "Model": { "Id": 1489, "Name": "New-York", "CountryId": 14, "OraId": 88, "DistrictId": 6, "Lat": 25.158855465, "Long": 7.4703558, "GoogleGeoId": "", "TimezoneId": 3, "AreaId": 4, "District": { "Id": 12, "Name": "Uganda", "OraId": 51, "Cities": null, "CountryId": 9, "OraParishId": 0 }, "Area": { "Id": 4, "Name": "New-Orlean", "DistrictId": 14, "CountryId": 88, "OraId": 666 }, "IsShowArea": false, "StoreId": 9, "DeliveryPointsNumber": 0, "MajorOrder": 1 } }
问题分析与优化方案
原代码存在逻辑问题:response.body("Model")获取到的是Model对应的对象,此时再用JsonPath.read(string, "$.Model")读取,会因为当前JSON根节点已是Model对象而找不到路径,导致报错。
以下是两种可行的优化写法:
方法1:直接通过Rest Assured的JsonPath提取并转字符串
利用Rest Assured内置的JsonPath直接定位到Model字段,调用toString()转换为字符串:
public static String returnCity(String CityId) { Response response = given().spec(returnRequest(token)) .when().get(Configuration.baseUrl + "/api/v1/city/" + CityId) .then() .log().all() .contentType(JSON) .assertThat() .statusCode(200) .extract().response(); // 直接提取Model对象并转为字符串 return response.jsonPath().get("Model").toString(); }
方法2:用Jackson的ObjectMapper序列化(标准JSON格式输出)
如果需要标准的JSON格式字符串,建议使用Jackson的ObjectMapper将Model对象序列化为JSON字符串,避免toString()产生的非标准格式:
import com.fasterxml.jackson.databind.ObjectMapper; public static String returnCity(String CityId) throws IOException { Response response = given().spec(returnRequest(token)) .when().get(Configuration.baseUrl + "/api/v1/city/" + CityId) .then() .log().all() .contentType(JSON) .assertThat() .statusCode(200) .extract().response(); // 提取Model对象 Object model = response.jsonPath().get("Model"); ObjectMapper objectMapper = new ObjectMapper(); // 序列化为标准JSON字符串 return objectMapper.writeValueAsString(model); }
内容的提问来源于stack exchange,提问作者Андрей Шамурадов
相关产品推荐
相关产品推荐

