响应正文未使用放心进行反序列化



当我尝试将响应体反序列化为 POJO 时,会设置空值,并且在不使用 JsonIgnoreProperties(ignoreUnknown = true( 时遇到以下错误: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段"City"(类TestNGMaven.restAssuredProject.WeatherInfo(,未标记为可忽略(6个已知属性:"湿度","温度","天气描述","城市","风速","风向度"](

以下是我正在使用的代码:

public class WeatherInfo
{
private String city;
private String temperature;
private String humidity;
private String weatherDescription;
private String windSpeed;
private String windDirectionDegree;
// getters and setters
}

使用方法:

public void getWeatherDetailsForCity(String city) {
RestAssured.baseURI="http://restapi.demoqa.com/utilities/weather/city";
Response response= given().
when().
get("/"+city)
.then()
.extract()
.response();
ResponseBody responseBody=response.body();
//No issues in below code
System.out.println(responseBody.asString());
//Exception for the below lines
WeatherInfo weatherInfo =responseBody.as(WeatherInfo.class);    
System.out.println(weatherInfo.getCity());

错误: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:无法识别的字段"City"(类TestNGMaven.restAssuredProject.WeatherInfo(,未标记为可忽略(6个已知属性:"湿度","温度","天气描述","城市","风速","风向度"]( 在 [来源: (字符串("{ "城市": "海得拉巴", "温度": "28.5摄氏度", "湿度": "62%", "天气描述": "雾霾", "风速": "每小时 1.5 公里", "风向度": "度" }">

将城市更改为城市也不能解决错误。

通过在我使用 GSON 注释样式的 POJO 类中添加以下内容来解决此问题

@SerializedName("City")
@Expose
private String city;

并使用以下格式反序列化

WeatherInfo weatherInfo =responseBody.as(WeatherInfo.class,ObjectMapperType.GSON);

相关内容

  • 没有找到相关文章

最新更新