【问题标题】:How to use custom types for Retrofit @Query parameters?如何为 Retrofit @Query 参数使用自定义类型?
【发布时间】:2018-01-08 23:17:57
【问题描述】:

给定以下Retrofit接口:

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

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

data class GeoLocation(
        val latitude: Double,
        val longitude: Double
)

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

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

这是改造设置:

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

    return Retrofit.Builder()
            .baseUrl(baseUrl)
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .client(okHttpClient)
            .build()
}

【问题讨论】:

  • 您可以使用接口默认方法并委托给较旧的方法,只需我的 2 美分。
  • @KirillRakhman 谢谢你的链接。我不明白的是如何使用Converter&lt;F, T&gt;GeoLocation 对象转换为latlon Double 值。
  • 目前看来这是不可能的。

标签: kotlin retrofit retrofit2


【解决方案1】:

如果您关心用户友好的访问,您可以创建一个包装函数。这样你就不用搞乱你的改造配置了

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>>

【讨论】:

  • 据我所知,Retrofit2 不允许在它应该实现的接口上使用未注释的函数,即使这些函数具有默认实现,这意味着这个包装函数需要在一个单独的类。
【解决方案2】:

您可以在挂起函数中使用 Query 作为参数:

@GET("Posts")
suspend fun getPosts(@Query("MaxCount") maxCount: Int): Response<Posts>

【讨论】:

  • 这与问题有什么关系?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-08
  • 2018-01-28
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2017-12-05
相关资源
最近更新 更多