In My case when I put sub class object in retrofit request it goes blank in request body
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);
now i am passing FbUserObject
networkAPI.createUserNew(fbUserObject).subscribe();
then object goes blank in body. see my log
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)
I also go through this stackover flow link Polymorphism with gson
Should i have to write my own Gson Converter?
Gson tries to serialize class User
which does not have fields.
What you need to do is to register type adapter to 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()));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With