2

Question regarding android. I am having a problem with retrofit (I am using moshi converter factory) and hope that you can help.

Basically I have a screen with 3 checkboxes. User is able to select any of these checkboxes, and also user is allowed to select none of them.

When user doesn't select any checkboxes and click complete button, I send a PATCH request to backend with a model which contains 3 null values.

Problem here is that PATCH request which is being sent doesn't include any properties which have been nulled.

I spent some time researching why retrofit/moshi doesn't serialize nulled properties and I found a fix.

So I have this line

.addConverterFactory(MoshiConverterFactory.create(moshi))

Which I replaced with

.addConverterFactory(MoshiConverterFactory.create(moshi).withNullSerialization())

Now nulls are serialized and I am able to send a PATCH request model with nulled values. However now I'm facing another problem. Across my app I'm using only one retrofit client and I don't want to serialize nulls for all requests. Also I don't want to create another retrofit client.

How can I fix this problem? As far as I've researched it seems that I need to add an adapter with toJson() and fromJson() methods and then somehow enable nullSerialization only for that adapter. However I don't completely understand that solution and not even sure how to handle it.

Comments
  • 2
    Solved my problem by adding secondary converter.

    I used this library https://github.com/jamesdeperio/...
    Full documentation here:https://jamesdeperio.github.io/retr...

    So my retrofit builder now looks like this:

    @Provides
    @Singleton
    fun provideRetrofit(application: Application, client: OkHttpClient, moshi: Moshi) = Retrofit.Builder()
    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
    .addConverterFactory(MoshiConverterFactory.create(moshi))
    .addConverterFactory(SerializationFormatFactory.Builder().setJSONConverterFactory(MoshiConverterFactory.create(moshi).withNullSerialization()).build())
    .client(client)
    .baseUrl(application.getString(R.string.api_base))
    .build()

    And then in the services api interface all I have to do is add annotation @JSONFormat and then this post request will include nulled parameter values into my post request
Add Comment