我有问题,真的不知道如何解决这个问题。我尝试了几天找到类似的帖子,但没有找到。
我使用改造来解析api并将其放入房间数据库并使用rxjava3,因为它将是异步的
我的 JSON
{
"coord": {
"lon": -0.1257,
"lat": 51.5085
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"base": "stations",
"main": {
"temp": 22.78,
"feels_like": 22.81,
"temp_min": 21.23,
"temp_max": 23.92,
"pressure": 1020,
"humidity": 65
},
"visibility": 10000,
"wind": {
"speed": 0.45,
"deg": 264,
"gust": 2.68
},
"clouds": {
"all": 75
},
"dt": 1623415339,
"sys": {
"type": 2,
"id": 2019646,
"country": "GB",
"sunrise": 1623383015,
"sunset": 1623442617
},
"timezone": 3600,
"id": 2643743,
"name": "London",
"cod": 200
}
API服务
interface OpenWeatherApiService {
@GET("weather")
fun getCurrentWeather(
@Query("q") location:String,
@Query("appid") key:String,
@Query("units") units:String,
@Query("lang") language:String = "en"
):Observable<CurrentWeatherResponse>}
我的应用模块
@Module
@InstallIn(ActivityComponent::class)
object AppModule {
@Provides
fun provideOkHttpClient() =if(BuildConfig.DEBUG) {
val interceptor = HttpLoggingInterceptor()
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY)
OkHttpClient
.Builder()
.addInterceptor(interceptor)
.build()
}else{
OkHttpClient
.Builder()
.build()
}
@Provides
fun provideRetrofit(okHttpClient: OkHttpClient): Retrofit = Retrofit.Builder()
.baseUrl("https:/api.openweathermap.org/data/2.5/")
.addCallAdapterFactory(RxJava3CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.client(okHttpClient)
.build()
@Provides
fun provideGson(): Gson = GsonBuilder().create()
@Provides
fun provideOpenWeatherApiService(retrofit: Retrofit):OpenWeatherApiService = retrofit.create(OpenWeatherApiService::class.java)
@Provides
fun provideOpenWeatherApiHelper(openWeatherApiHelper: OpenWeatherApiHelperImpl):OpenWeatherApiHelper = openWeatherApiHelper
@Provides
fun provideForecastDatabase(@ApplicationContext appContext: Context) = ForecastDatabase.getDatabase(appContext)
@Provides
fun provideCurrentWeatherDao(db: ForecastDatabase) = db.currentWeatherDao()
}
我的回复
const val CURRENT_WEATHER_ID = 0
@Entity(tableName = "current_weather")
data class CurrentWeatherResponse(
val main: List<Main> ,
val name: String? = "",
val visibility: Int? = 0,
val weather: List<Weather> ,
val wind:List<Wind>
){
@PrimaryKey(autoGenerate = false)
var id_current_weather:Int = CURRENT_WEATHER_ID
}
我的 Main 类型转换器,我把它放在数据库中
class MainConverter {
val gson = Gson()
@TypeConverter
fun listMainToString(mainList: List<Main?>?):String?{
return gson.toJson(mainList)
}
@TypeConverter
fun stringToListMain(dataMain:String?):List<Main?>?{
if (dataMain == null){
return Collections.emptyList()
}
val listType: Type = object :
TypeToken<List<Main>?>() {}.type
return gson.fromJson<List<Main?>?>(dataMain,listType)
}
}