如何为 Retrofit @Query 参数使用自定义类型? [英] How to use custom types for Retrofit @Query parameters?

查看:70
本文介绍了如何为 Retrofit @Query 参数使用自定义类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定以下 Retrofit 接口:

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

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

How can I replace the location parameters with a more user friendly GeoLocation type ...

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

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

... which is automatically converted to lat and lon at request time such as:

@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()
}

推荐答案

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

If userfriendly access is your concern, you could just create a wrapper function. This way you don't have to mess with your Retrofit configuration at all

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

这篇关于如何为 Retrofit @Query 参数使用自定义类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆