改造了,你可以用一个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到您的改造实例
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);
参见本[元讨论(http://meta.stackoverflow.com/q/327487/230513)。 – trashgod