使用@Field("json")
而不是@Body
在您的端點定義:
@POST("/login")
public Observable<DataLogin> getLogin(@Field("json") LoginRequest loginRequest);
而且,你必須使用轉換器轉換的對象。以下是GSON的示例。您基本上需要爲默認的GsonConverterFactory
創建自定義包裝,因爲它沒有實現stringConverter(...)
方法,該方法將用@Field
等註釋的值轉換爲字符串。
public class GsonStringConverterFactoryWrapper extends Converter.Factory {
private GsonConverterFactory converterFactory;
public static GsonStringConverterFactoryWrapper create() {
return create(new Gson());
}
@SuppressWarnings("ConstantConditions")
public static GsonStringConverterFactoryWrapper create(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
return new GsonStringConverterFactoryWrapper(gson);
}
private final Gson gson;
private GsonStringConverterFactoryWrapper(Gson gson) {
this.gson = gson;
converterFactory = GsonConverterFactory.create(gson);
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations,
Retrofit retrofit) {
return converterFactory.responseBodyConverter(type, annotations, retrofit);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type,
Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return converterFactory.requestBodyConverter(type, parameterAnnotations, methodAnnotations, retrofit);
}
@Nullable
@Override
public Converter<?, String> stringConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new GsonStringConverter<>(gson);
}
public static class GsonStringConverter<T> implements Converter<T, String> {
private final Gson gson;
GsonStringConverter(Gson gson) {
this.gson = gson;
}
@Override
public String convert(@NonNull T value) throws IOException {
return gson.toJson(value);
}
}
}
然後,當你創建的改造實例,只需使用該適配器:
new Retrofit.Builder()
.addConverterFactory(GsonStringConverterFactoryWrapper.create(gson)) // if you don't have a custom GSON instance, just call .create()
// [...] other settings
.build();
工作很好,謝謝。 –
現在我可以執行但總是返回無法進行身份驗證,檢查它,似乎我的對象爲空,但不明白爲什麼。 –
我不知道你使用了什麼樣的轉換器工廠,但似乎'GsonConverterFactory'沒有實現'stringConverter'。我會更新答案,爲GSON創建一個新的轉換器。 –