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

编程入门 行业动态 更新时间:2024-10-25 02:23:36
本文介绍了如何为 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 )

... 在请求时自动转换为 lat 和 lon 如:

... 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 参数使用自定义类型?

本文发布于:2023-10-19 14:42:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1507828.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:自定义   何为   参数   类型   Query

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!