CPS251 Android Development by Scott Shaper

Building the WeatherResponse Models

The WeatherResponse file contains Kotlin data classes that represent the JSON returned by OpenWeatherMap. These classes let Retrofit and Gson map JSON fields into Kotlin objects automatically.

data class WeatherResponse(
    val coord: Coord,
    val weather: List,
    val base: String,
    val main: Main,
    val visibility: Int,
    val wind: Wind,
    val clouds: Clouds,
    val dt: Long,
    val sys: Sys,
    val timezone: Int,
    val id: Int,
    val name: String,
    val cod: Int
)

data class Coord(
    val lon: Double,
    val lat: Double
)

data class Weather(
    val id: Int,
    val main: String,
    val description: String,
    val icon: String
)

data class Main(
    val temp: Double,
    val feels_like: Double,
    val temp_min: Double,
    val temp_max: Double,
    val pressure: Int,
    val humidity: Int,
    val sea_level: Int?,
    val grnd_level: Int?
)

data class Wind(
    val speed: Double,
    val deg: Int,
    val gust: Double?
)

data class Clouds(
    val all: Int
)

data class Sys(
    val type: Int?,
    val id: Int?,
    val country: String,
    val sunrise: Long,
    val sunset: Long
)

Code Explanation

Why Data Classes?

Top-Level Response Object

Nested Models

Nullable Fields

Matching JSON Keys

How the UI Uses This Model

Learning Aids

Tips for Success

  • Start by modeling only the fields your app needs, then add more later if needed.
  • Use nullable types for fields that may not always be returned.
  • Keep model classes small and focused on data only.
  • Group related nested JSON objects into separate data classes.
  • Check sample JSON from the API docs while building these models.

Common Mistakes to Avoid

  • Using non-null types for optional fields, which can cause parsing failures.
  • Misspelling field names so they no longer match JSON keys.
  • Treating array fields (like weather) as single objects.
  • Putting business logic into data model classes.
  • Ignoring units and value meaning (for example, metric vs imperial temperature values).

Best Practices

  • Keep response models in a dedicated package, such as api or model.
  • Use clear type choices (Double, Int, Long) based on API docs.
  • Prefer immutable properties with val for API responses.
  • Handle nulls in the ViewModel or UI with safe calls and defaults.
  • Update your models whenever API response formats change.