使用gson将json反序列化为java会导致空字段

pgvzfuti  于 2021-07-08  发布在  Java
关注(0)|答案(2)|浏览(432)

我使用gson从api解析json响应。但当我试图得到的内容是空的。
我的序列化类:

class Weather {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("main")
@Expose
private String main;
@SerializedName("description")
@Expose
private String description;
@SerializedName("icon")
@Expose
private String icon;

public Integer getId() {
    return id;
}

public void setId(Integer id) {
    this.id = id;
}

public String getMain() {
    return main;
}

public void setMain(String main) {
    this.main = main;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getIcon() {
    return icon;
}

public void setIcon(String icon) {
    this.icon = icon;
}

}
我的电话:

Gson gson = new GsonBuilder().create();
        Weather weather = gson.fromJson("{\"weather\":[{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}]}", Weather.class);
        Log.i("[Weather]", "Weather: " + weather.getDescription());

说明和其他字段都是空的我不明白为什么?

5cg8jx4n

5cg8jx4n1#

您为模型类创建了一个json数组项,而不是为完整的json对象。创建一个新的可序列化类,例如weatherobject,如下所示

class WeatherObject {
@SerializedName("weather")
@Expose
private ArrayList<Weather> weather;
// getters and setters
}

在中使用此类 gson.fromJson 方法

o7jaxewo

o7jaxewo2#

与其传递完整的json,不如只传递数组中与“weather”相关联的内容,如下所示:

Weather weather = gson.fromJson("{\"id\":800,\"main\":\"Clear\",\"description\":\"clear sky\",\"icon\":\"01n\"}", Weather.class);

相关问题