gpt4 book ai didi

retrofit2 - Retrofit 能否将 @Path 参数从自定义类转换为原始类型

转载 作者:行者123 更新时间:2023-12-05 02:58:54 25 4
gpt4 key购买 nike

我有以下 retrofit 请求:

@GET("event/{id}")
suspend fun getEvent(@Path("id") eventId: Long): Response<Event>

但是在我的应用程序中,我对事件 ID 使用了以下包装器:

data class EventId(val value: Long)

是否可以将 EventId 类作为路径参数传递,并以某种方式告诉 Retrofit 如何将值转换为 Long?这是我想要的方法签名:

@GET("event/{id}")
suspend fun getEvent(@Path("id") eventId: EventId): Response<Event>

最佳答案

我找到的解决方案是在 Retrofit Builder 中注册转换器工厂:

class EventIdConverterFactory : Converter.Factory() {
override fun stringConverter(type: Type, annotations: Array<Annotation>, retrofit: Retrofit) =
if (type == EventId::class.java) {
Converter<Any, String> { (it as EventId).value.toString() }
} else {
super.stringConverter(type, annotations, retrofit)
}
}

关于retrofit2 - Retrofit 能否将 @Path 参数从自定义类转换为原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58508441/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com