我的代码应该进行天气 API 调用并使用序列化将数据存储到数据类中,但是日志中的数据为空。当我删除序列名称并将变量命名为与序列名称完全相同时,它可以正常工作。
改造:
object RetrofitInstance {
private const val BASE_URL = "https://api.open-meteo.com/"
val instance: WeatherAPI by lazy {
val retrofit = Retrofit.Builder()
.baseUrl(RetrofitInstance.BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
retrofit.create(WeatherAPI::class.java)
}
}
API调用及数据存储:
api.getWeatherData(
location.latitude,
location.longitude,
"temperature_2m,relative_humidity_2m,apparent_temperature,precipitation,weather_code,wind_speed_10m,wind_direction_10m",
"visibility",
"temperature_2m_max,temperature_2m_min,sunrise,sunset,daylight_duration,uv_index_max",
"auto",
1
).enqueue(object : Callback<WeatherResults> { // Change to WeatherResults
@RequiresApi(Build.VERSION_CODES.O)
override fun onResponse(call: Call<WeatherResults>, response: Response<WeatherResults>) {
// Provide more detailed error messages based on response code if necessary
if (response.isSuccessful) {
response.body()?.let {
weatherCache.updateCache(it) // Update the weather cache
Log.d("API Call", "Full API Response: ${response.body()}")
onSuccess(it)
} ?: onFailure(Throwable("Response body is null"))
} else {
onFailure(Throwable("Error: ${response.code()}"))
}
}
override fun onFailure(call: Call<WeatherResults>, t: Throwable) {
onFailure(t)
}
})
数据类
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
@Serializable
data class WeatherResults(
val current: Current? = null,
val daily: Daily? = null,
val hourly: Hourly? = null
)
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
@Serializable
data class Current(
@SerialName("temperature_2m") val temperature: Double?, // Works as expected
@SerialName("apparent_temperature") val apparentTemperature: Double?,
@SerialName("relative_humidity_2m") val relativeHumidity: Int?, // Matches JSON
@SerialName("weather_code") val weatherCode: Int?,
@SerialName("wind_speed_10m") val windSpeed: Double?,
@SerialName("wind_direction_10m") val windDirection: Double?,
val visibility: Int?,
val time: String
)
import kotlinx.serialization.Serializable
import kotlinx.serialization.SerialName
@Serializable
data class Daily(
val time: List<String?>?,
@SerialName("weather_code") val weatherCode: List<Int?>?,
@SerialName("temperature_2m_max") val temperatureMax: List<Double?>?,
@SerialName("temperature_2m_min") val temperatureMin: List<Double?>?,
@SerialName("precipitation_probability_max") val precipitationProbability: List<Int?>?,
@SerialName("apparent_temperature_max") val apparentTemperatureMax: List<Double?>?,
@SerialName("apparent_temperature_min") val apparentTemperatureMin: List<Double?>?,
val sunrise: List<String?>?,
val sunset: List<String?>?,
@SerialName("sunshine_duration") val sunshineDuration: List<Double?>?,
@SerialName("uv_index_max") val uvIndexMax: List<Double?>?
)
我尝试删除序列化并相应地命名变量,并且数据存储正确。我还检查了我的 gradle 和插件/依赖项是最新的。
解决了,我必须修复我的 RetrofitInstance 类以包含 JSON 解析
object RetrofitInstance {
fun getInstance(): WeatherAPI {
val retrofit = Retrofit.Builder()
.baseUrl(BASE_URL)
.apply {
addConverterFactory(
Json { ignoreUnknownKeys = true }
.asConverterFactory("application/json".toMediaType())
)
}
.build()
return retrofit.create(WeatherAPI::class.java)
}
}