ResponseBody不会使用反保证来反序列化

时间:2018-10-13 16:34:00

标签: json rest deserialization pojo rest-assured

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

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

    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个已知属性:“湿度”,“温度”,“天气描述”,“城市” ,“ windSpeed”,“ windDirectionDegree”])  在[来源:(字符串)” {     “城市”:“海得拉巴”,     “温度”:“ 28.5摄氏度”,     “湿度”:“ 62%”,     “ WeatherDescription”:“阴霾”,     “ WindSpeed”:“每小时1.5公里”,     “ WindDirectionDegree”:“学位” }“

将城市更改为城市也无法解决错误。

1 个答案:

答案 0 :(得分:0)

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

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

并使用以下格式反序列化

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