Retrofit 有一个 Converter.Factory 抽象类,您可以使用它来进行自定义 HTTP 表示。如果方法有特定的注解,您可以创建一个 Converter 来构造 okhttp.RequestBody。
最终结果将如下所示:
@POST("/")
Call<Void> postBar(@Body @Root("bar") String foo)
并转换:postBar("Hello World")
进入{ "bar" : "Hello World" }。
让我们开始吧。
第 1 步 - 为根键 (Root.java) 创建注释
/**
* Denotes the root key of a JSON request.
* <p>
* Simple Example:
* <pre><code>
* @POST("/")
* Call<ResponseBody> example(
* @Root("name") String yourName);
* </code></pre>
* Calling with {@code foo.example("Bob")} yields a request body of
* <code>{name=>"Bob"}</code>.
* @see JSONConverterFactory
*/
@Documented
@Target(PARAMETER)
@Retention(RUNTIME)
public @interface Root {
/**
* The value of the JSON root.
* Results in {"value" : object}
*/
String value();
}
第 2 步 - 定义检测注释的 Converter.Factory (JSONConverterFactory.java)。我使用Gson 进行 JSON 解析,但你可以使用任何你想要的框架。
/**
* Converts @Root("key") Value to {"key":json value} using the provided Gson converter.
*/
class JSONConverterFactory extends Converter.Factory {
private final Gson gson;
private static final MediaType CONTENT_TYPE =
MediaType.parse("application/json");
JSONConverterFactory(Gson gson) {
this.gson = gson;
}
@Override
public Converter<?, RequestBody> requestBodyConverter(
Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
for (Annotation annotation : parameterAnnotations) {
if (annotation instanceof Root) {
Root rootAnnotation = (Root) annotation;
return new JSONRootConverter<>(gson, rootAnnotation.value());
}
}
return null;
}
private final class JSONRootConverter<T> implements Converter<T, RequestBody> {
private Gson gson;
private String rootKey;
private JSONRootConverter(Gson gson, String rootKey) {
this.gson = gson;
this.rootKey = rootKey;
}
@Override
public RequestBody convert(T value) throws IOException {
JsonElement element = gson.toJsonTree(value);
JsonObject object = new JsonObject();
object.add(this.rootKey, element);
return RequestBody.create(CONTENT_TYPE, this.gson.toJson(object));
}
}
}
第 3 步 - 将 JSONConverterFactory 安装到您的 Retrofit 实例中
Gson gson = new GsonBuilder().create(); // Or your customized version
Retrofit.Builder builder = ...;
builder.addConverterFactory(new JSONConverterFactory(gson))
第 4 步 - 利润
@POST("/")
Call<Void> postBar(@Body @Root("bar") String foo)
或者对于您的情况:
@POST("foo/{fooId}/bars")
Observable<Void> postBar(@Body @Root("bar") String barValue, @Path("fooId") String styleId);