kksi
kksi

Reputation: 33

Passing Realm object as Retrofit 2 PUT request body

I am trying to use RealmObject as a PUT message body content in Retrofit 2. I have implemented custom Gson with JsonSerializer and it works fine outside of Retrofit, but I am still not getting object data in request body.
Gradle build for retrofit and gson:

compile 'com.google.code.gson:gson:2.6.2'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'

Retrofit service:

public interface LogstashRetrofitService {
    @PUT(LOGSTASH_SERVER_PATH)
    Call<ResponseBody> putLogstashMessage(@Body LogstashMessage logstashMessage);
}


Building Retrofit:

Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(LOGSTASH_SERVER_HOST)
            .addConverterFactory(GsonConverterFactory.create(RealmObjectGsonBuilder.getRealmGson()))
            .client(httpClient.build())
            .build();
logstashRetrofitService = retrofit.create(LogstashRetrofitService.class);
logstashRetrofitService.putLogstashMessage(logstashMessage).enqueue(new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {}
        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {}
    });

Upvotes: 2

Views: 1074

Answers (1)

EpicPandaForce
EpicPandaForce

Reputation: 81539

It's because GSON tries to serialize your object based on fields using reflection, but the Realm instance data is only accessible through the proxy getter setter methods.

See related open issue because GSON doesn't really care and therefore doesn't have config to use the getters/setters instead https://github.com/google/gson/issues/232

This is possible with Jackson or LoganSquare json parsers.

Or, you need to make an unmanaged copy of your RealmObject, which can be done with realmObject.copyFromRealm() which creates a deep copy of your class, detached from the Realm.

Upvotes: 7

Related Questions