在我的例子中,当我将子类对象放入改造请求中时,它在请求正文中变为空白
interface User{ // my super interface
}
class FbUser implements User{ // my sub class
public String name;
public String email;
}
interface APIInterface{
@POST(APIConstants.LOGIN_URL)
Observable<LoginAPIResponse> createUserNew(@Body User user);
}
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(new Gson()))
.addCallAdapterFactory(RxErrorHandlingCallAdapterFactory.create())
.client(okHttpClient)
.build();
APIInterface networkAPI = retrofit.create(APIInterface.class);
现在我正在传递 FbUserObject
networkAPI.createUserNew(fbUserObject).subscribe();
然后对象在主体中变为空白。 查看我的日志
D/OkHttp: Content-Type: application/json; charset=UTF-8
D/OkHttp: Content-Length: 2
D/OkHttp: Accept: application/json
D/OkHttp: TT-Mobile-Post: post
D/OkHttp: {}
D/OkHttp: --> END POST (2-byte body)
我还浏览了这个 stackover 流程链接 Polymorphism with gson
我必须自己编写 Gson 转换器吗?
最佳答案
Gson 尝试序列化没有字段的 User
类。
你需要做的是将类型适配器注册到gson:
retrofitBuilder.addConverterFactory(GsonConverterFactory.create(new GsonBuilder()
.registerTypeAdapter(User.class, new JsonSerializer<User>() {
@Override
public JsonElement serialize(User src, Type typeOfSrc, JsonSerializationContext context) {
if (src instanceof FbUser ) {
return context.serialize(src, FbUser.class);
}
return context.serialize(src);
}
}).create()));
关于java - 无法使用 GsonConverterFactory 在 Retrofit 2.0 中将子类对象转换为请求正文 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37589236/