gpt4 book ai didi

java - Retrofit/GSON 中嵌套对象的数据模型

转载 作者:行者123 更新时间:2023-12-02 09:48:50 25 4
gpt4 key购买 nike

我正在使用远程天气 API 并从中获取以下数据。我正在使用 Retrofit 调用电话,并且使用 GSON。

{"coord":{"lon":127.08,"lat":37.51},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50n"},
{"id":721,"main":"Haze","description":"haze","icon":"50n"}],"base":"stations",
"main":{"temp":18,"pressure":1013,"humidity":82,"temp_min":17,"temp_max":19},
"visibility":9000,"wind":{"speed":1.5,"deg":160},"clouds":{"all":40},"dt":1559762819,
"sys":{"type":1,"id":8096,"message":0.0054,"country":"KR","sunrise":1559765465,
"sunset":1559818179},"timezone":32400,"id":1837217,"name":"Sinch’ŏn-dong","cod":200}

我有一个名为天气的数据模型。如果我希望我的数据模型也支持 wind,我是否必须为其创建一个单独的数据模型,因为它嵌套在我上面显示的 JSON 响应中?

最佳答案

您得到的响应是一个同时包含天气的对象,我们将其称为WeatherResponse。简化的 JSON 如下:

{
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50n"
},
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"wind": {
"speed": 1.5,
"deg": 160
}
}

您的 Retrofit API 中可能有类似的内容:

@GET("weather")
Call<WeatherResponse> getWeather();

其中 WeatherResponse 看起来像:

public class WeatherResponse {
public Collection<Weather> weather;
public Wind wind; // You need to add & implement this!
}

如果您已经可以解析您的天气,它应该如下所示:

public class Weather {
public Long id;
public String main;
public String description;
public String icon;
}

并且您需要实现类Wind,例如:

public class Wind {
public Double speed;
public Integer deg;

}

(我已将所有字段声明为公共(public),只是为了缩短代码,因此省略了 getter 和 setter。)

关于java - Retrofit/GSON 中嵌套对象的数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56467243/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com