我正在使用远程天气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响应中?
答案 0 :(得分:1)
您得到的响应是同时包含天气和风的对象,我们将其称为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!
}
如果您已经可以解析Weather
,则其外观应为:
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;
}
(我已将所有字段声明为公共字段,只是为了缩短代码,从而省略了getter和setter。)
答案 1 :(得分:0)
实际上,您可以通过为每个对象创建一个模型类并将其作为变量放在外部类中来实现。但是,这很耗时
建议
json to java/kotlin
,他们会为您转化答案 2 :(得分:0)
是的,您必须创建一个新的数据模型。并小心处理可能的空值。这是科特林的例子 而且,就个人而言。我更喜欢手动创建模型而不是使用工具,通过自己完成模型,您可以实现很多事情,例如命名,可能的null值和不需要的数据
import com.google.gson.annotations.SerializedName
data class AdReplyRequest(@SerializedName("cc_sender") val cc_sender: Boolean,
@SerializedName("message") val message: AdReplyMessage)
data class AdReplyMessage(@SerializedName("body") val message: String,
@SerializedName("email") val email: String,
@SerializedName("name") val name: String,
@SerializedName("phone") val phone: String)