1

I have class like this:

class MyData {

    @SerializedName("name")
    var name: String? = null

    @SerializedName("surName")
    var surName: String? = null
    
}

My service calls is like this.

interface MyServiceCall {
    
    @PUT("/My/endPoint")
    fun updateInfo(@Body info: MyData): Flowable<Response<ResponseBody>>

}

But when I want to send only name and surname null. The null dont go to backend and then return 400 - Bad Request.

So my question is How can I send data to backend even fields are null?

Emanuel Garcia
  • 325
  • 2
  • 11

1 Answers1

6

Apply serializeNulls() in GsonBuilder() when adding converterFactory for Retrofit object :

 retrofit = new Retrofit.Builder().baseUrl("YOUR BASE URL")
    .addConverterFactory(GsonConverterFactory.create(new GsonBuilder().serializeNulls().create()))
    .build();
Nilesh B
  • 937
  • 1
  • 9
  • 14
  • 2
    How can I add `seializeNulls()` for a specific function? – Avramo Jan 20 '22 at 15:41
  • You have to create another retrofit client with this config to utilize it for such API calls ORyou should use overriden JsonBody like val body: RequestBody = RequestBody.create( "application/json; charset=utf-8".toMediaTypeOrNull(), JSONObject( GsonBuilder().serializeNulls().create().toJson( PrdUpdatePOJO( target = null ) ) ).toString() ) – Stan Jun 08 '22 at 11:48