Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can not convert Subclass object to request body json in Retrofit 2.0 with GsonConverterFactory

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?

like image 953
Ankur Samarya Avatar asked Jun 02 '16 10:06

Ankur Samarya


1 Answers

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()));
like image 62
pixel Avatar answered Oct 22 '22 00:10

pixel