Reputation: 1875
I'm using a remote weather API and got the following data from it. I'm making calls with Retrofit and I use 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}
I have a single data model named Weather. If I want my data model to also support wind do I have to create a separate data model for it because it's nested in the JSON response which I showed above?
Upvotes: 0
Views: 1313
Reputation: 12215
The response you get is an object that holds both Weather and Wind let us call it WeatherResponse
. Simplified JSON is like:
{
"weather": [
{
"id": 701,
"main": "Mist",
"description": "mist",
"icon": "50n"
},
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
}
],
"wind": {
"speed": 1.5,
"deg": 160
}
}
You might have something like this in your Retrofit API:
@GET("weather")
Call<WeatherResponse> getWeather();
where WeatherResponse
looks like:
public class WeatherResponse {
public Collection<Weather> weather;
public Wind wind; // You need to add & implement this!
}
If you already can parse your Weather
it should look like:
public class Weather {
public Long id;
public String main;
public String description;
public String icon;
}
and you need to implement the class Wind
like:
public class Wind {
public Double speed;
public Integer deg;
}
(I have declared all the fields public just to shorten the code so omitting getters & setters.)
Upvotes: 1
Reputation: 21
yes, you have to create a new data model. And be careful with handling possible null vales. Here is a kotlin example And, personally. I prefer to do the model manually instead of using a tool, by doing it by yourself you can realize of many things, like naming, possible null values and not needed data
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)
Upvotes: 0
Reputation: 2966
Actually you can do this by creating one model class for each object and place them as a variable in outer class. However, it is time consuming
Suggestions
json to java/kotlin
they will convert for youUpvotes: 0