如何为 Retrofit @Query 参数使用自定义类型?

JJD*_*JJD 8 kotlin retrofit retrofit2

给定以下Retrofit接口:

@GET("offices")
fun getOffices(@Query("uid") uid: String,
               @Query("lat") latitude: Double,
               @Query("lon") longitude: Double
): Call<List<Office>>
Run Code Online (Sandbox Code Playgroud)

如何用更用户友好的GeoLocation类型替换位置参数...

data class GeoLocation(
        val latitude: Double,
        val longitude: Double
)
Run Code Online (Sandbox Code Playgroud)

...在请求时自动转换为latlon,例如:

@GET("offices")
fun getOffices(@Query("uid") uid: String,
               @Query("location") location: GeoLocation
): Call<List<Office>>
Run Code Online (Sandbox Code Playgroud)

这是改造设置:

fun createRetrofit(baseUrl: String,
                   okHttpClient: OkHttpClient): Retrofit {
    val moshi = Moshi.Builder()
            .build()

    return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .client(okHttpClient)
            .build()
}
Run Code Online (Sandbox Code Playgroud)

Loo*_*oki 3

如果您关心用户友好的访问,您可以创建一个包装函数。这样您就不必弄乱您的 Retrofit 配置

fun getOffices(uid: String, location: GeoLocation): Call<List<Office>> {
    return getOfficesIf(uid, location.lat, location.lon)
}

@GET("offices")
fun getOfficesIf(@Query("uid") uid: String,
                 @Query("lat") latitude: Double,
                 @Query("lon") longitude: Double
): Call<List<Office>>
Run Code Online (Sandbox Code Playgroud)