Retrofit 是否支持将 JSON 作为参数传递,而将其作为普通参数调用? [英] Does Retrofit support passing JSON as parameter, yet call it as normal parameters?
问题描述
在对服务器的某些 API 调用上,而不是接口的正常参数,如下所示:
On some API calls to the server, instead of the normal parameters to the interface, like this:
interface SomeInterface {
@POST("first_launch") fun sendFirstLaunch(
@Path("referral_code") referralCode: String?,
@Path("referral_source") referralSource: String?): Call<BaseDCResponse>
}
我们实际上需要将这些参数作为正文中的 JSON 发送.
We actually need to send those parameters as a JSON in the body.
我不是改造专家,但根据我的发现(这里 为例),我只能向接口传递一个Json String,意思是:
I'm not an expert in Retrofit, but according to what I've found (here for example), I can only pass a Json String to the interface, meaning:
interface SomeInterface {
@POST("first_launch") fun sendFirstLaunch(@Body jsonString: String): Call<BaseDCResponse>
}
根据此处,我相信我也可以发送序列化对象.意思是这样的:
According to here, I believe I can also send a serialized object, instead. Meaning something like:
interface SomeInterface {
class SendFirstLaunchRequest(@Path("referral_code") val referralCode: String?,
@Path("referral_source") val referralSource: String?)
@POST("first_launch") fun sendFirstLaunch(
@Body body: SendFirstLaunchRequest): Call<BaseDCResponse>
}
这失去了访问函数的好方法,同时让我为我放在界面上的每个函数手动添加 Json 数据(或创建新类以传递那里).我想避免这种情况,并有一些类似于原始的东西.
This loses the nice way to reach the function, while making me add the Json data manually for each function I put on the interface (or create new classes to pass there). I want to avoid this, and have something similar to the original.
我试图越来越多地搜索有关此内容的信息,但似乎没有人要求这样做.
I tried to search more and more about this, but it doesn't seem like this was requested.
也许我看到了答案但没看懂.
Maybe I saw the answers but didn't understand them.
我认为即使是官方网站也显示了一些线索:
I think even the official website shows some clues about this:
https://square.github.io/retrofit/
看到我认为不可能,我也添加了一个请求这里.
Seeing that I don't think it's possible, I've also added a request for it here.
Retrofit 是否允许将我设置的参数发送给函数,将 Json 数据作为主体发送?
Does Retrofit allow to send the parameters I set to the function, to be a Json data as a body?
如果没有,有什么好的解决方法吗?我是否正确,我只能传递一个序列化的对象?如果是这样,正确的方法是什么?也许像这里?
If not, is there any nice workaround for this? Am I correct that I could only pass a serialized object instead? If so, what's the proper way to do it? Maybe like here?
推荐答案
似乎没有,并且有人请求提供一些东西来帮助处理这个问题:
Seems it doesn't, and that there is a request to offer something to help handling with this:
https://github.com/square/retrofit/issues/2890
这篇关于Retrofit 是否支持将 JSON 作为参数传递,而将其作为普通参数调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!