我可以在改造方法声明中使用可变参数吗? [英] Can I use varargs in a retrofit method declaration?
问题描述
我有一个 API 端点定义为:
I've got an API endpoint that is defined as:
GET https://api-server.com/something/{id_or_ids}
其中 ids
可以是单个对象 ID 或逗号分隔的 ID 列表.
例如https://api-server.com/something/abcd1234
https://api-server.com/something/abcd1234,abcd4567,gdht64332
where ids
can be a single object id or a comma separated list of ids.
e.g.
https://api-server.com/something/abcd1234
https://api-server.com/something/abcd1234,abcd4567,gdht64332
如果给出了单个 id(并且找到了匹配的对象),我会返回一个 json 对象:{ "blah" : "blah" }
if a single id is given (and a matching object is found) I get back a json object:
{ "blah" : "blah" }
如果给出多个 id,我会在 json 数组中得到响应:[{"blah1":"bleh"}, {"blah2":"meh"}, {"blah3":"blah"}]
If multiple ids are given, I get the response in a json array:
[{"blah1":"bleh"}, {"blah2":"meh"}, {"blah3":"blah"}]
我目前认为我应该将其实现为两种方法(可以用一种方法完成吗?):
I'm currently thinking that I should implement this as two methods (can it be done in one?):
采用单个 ID 并返回单个对象:
@GET("/something/{id}")
void getObject (@Path("id") String objectId, Callback<MyObject> callback)
和
接受多个 id 并返回一组对象.
@GET("/something/{ids}")
void getObject (Callback<MyObject[]> callback,@Path("ids") String ... objectIds)
有没有办法提供第二种方法 varargs 并将它们连接到 id 字段中?
Is there a way to feed the 2nd method varargs and concatenate them in the id field?
谢谢
推荐答案
Retrofit 不知道你想如何加入路径中的字符串.虽然逗号似乎很明显,但没有理由有人想要管道 (|
) 或冒号 (:
) 或其他任何东西.
Retrofit can't know how you want to join the strings in the path. While commas seem obvious, there's no reason why someone might want pipes (|
) or colons (:
) or whatever.
正因为如此,我们什么都不做,全靠你来选择.
Because of this fact, we don't do anything and rely on you to choose.
有两种解决方案:
使用
String
作为参数类型并在调用站点加入.例如:
Use
String
as the argument type and join at the call site. For example:
foo.getObject(Joiner.on(',').join(things));
使用自定义对象,其 toString()
方法处理返回一个或多个对象的正确格式.
Use a custom object whose toString()
method deals with returning the correct format for one or many objects.
这篇关于我可以在改造方法声明中使用可变参数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!