Retrofit解析OpenWeather接口报Expected BEGIN_ARRAY but was BEGIN_OBJECT错误
问题原因
报错Expected BEGIN_ARRAY but was BEGIN_OBJECT at path $.main是因为接口返回的JSON结构和你定义的解析实体类字段类型不匹配:
- 返回JSON中
main、wind字段都是单个JSON对象,不是数组 - 但你在
CurrentWeatherResponse中将main定义为List<Main>、wind定义为List<Wind>,Gson解析时预期接收数组结构,实际收到对象结构,直接抛出异常。 - 该错误发生在Retrofit解析接口返回的阶段,还未到Room存储步骤,你当前编写的List类型转换器无法解决这个解析问题。
解决方案
步骤1:修正响应实体类字段类型
将main、wind字段改为和JSON结构匹配的单个对象类型,weather字段本身是数组,保持List类型即可:
const val CURRENT_WEATHER_ID = 0 @Entity(tableName = "current_weather") data class CurrentWeatherResponse( val main: Main, val name: String? = "", val visibility: Int? = 0, val weather: List<Weather>, val wind: Wind ){ @PrimaryKey(autoGenerate = false) var id_current_weather:Int = CURRENT_WEATHER_ID }
步骤2:适配Room存储的类型转换器
Room无法直接存储自定义对象,需要编写对应单个类型的转换器,替换之前的List转换器:
class WeatherTypeConverter { private val gson = Gson() // Main类型转换 @TypeConverter fun mainToString(main: Main?): String? = gson.toJson(main) @TypeConverter fun stringToMain(data: String?): Main? = gson.fromJson(data, Main::class.java) // Wind类型转换 @TypeConverter fun windToString(wind: Wind?): String? = gson.toJson(wind) @TypeConverter fun stringToWind(data: String?): Wind? = gson.fromJson(data, Wind::class.java) // Weather数组类型转换 @TypeConverter fun weatherListToString(weatherList: List<Weather>?): String? = gson.toJson(weatherList) @TypeConverter fun stringToWeatherList(data: String?): List<Weather>? { if (data == null) return emptyList() val listType = object : TypeToken<List<Weather>>() {}.type return gson.fromJson(data, listType) } }
之后将该转换器注册到你的ForecastDatabase类上:
@Database(entities = [CurrentWeatherResponse::class], version = 1) @TypeConverters(WeatherTypeConverter::class) abstract class ForecastDatabase : RoomDatabase() { // 原有Dao定义和单例逻辑保持不变 }
额外注意
你当前配置的Retrofit baseUrl少了一个斜杠,正确写法为:https://api.openweathermap.org/data/2.5/
避免后续接口请求出错。
内容的提问来源于stack exchange,提问作者ManForProm
相关产品推荐
相关产品推荐

