10

I need to pass the keys even with no values as the keys are mandatory at the server side. But Retrofit was removing the keys with null values while sending the request. How I can achieve sending keys without values to the server with the use of Retrofit?

Request body look like this :

{
        "first_name":"testlogin",
        "last_name":"lastname",
        "username":"testman", 
        "password":"test123", 
        "email":"tester@test.com", 
        "address1":"123+test+way",
        **"address2":"",**
        **"address3":"",**
        "postal_code":"75023",
        "country":1,
        **"state":""**
}

Thanks in advance.

shim
  • 9,289
  • 12
  • 69
  • 108
NagarjunaAlaparthi
  • 101
  • 1
  • 1
  • 5
  • An empty string is not a null value. Can you not `setState("")`, for example? – OneCricketeer Oct 15 '16 at 14:03
  • Thanks @cricket_007 but Retrofit not sending keys with empty string value also... – NagarjunaAlaparthi Oct 15 '16 at 14:04
  • 1
    Are you using the Gson converter? – OneCricketeer Oct 15 '16 at 14:06
  • yes, I am converting the model into string using Gson converter and sending it as Body... After Gson conversion string has the keys with empty strings. Above json object is after the conversion.. – NagarjunaAlaparthi Oct 15 '16 at 14:08
  • 1
    I haven't used Gson in a while, but my guess is that Gson is removing empty/null values from the JSON object, not Retrofit. – OneCricketeer Oct 15 '16 at 14:09
  • `Gson` is, indeed, removing the `null` values by default. This is a dangerous default, I find, I should be changed. For example, delete the value of a field on a mobile device and send to a JSON web service with Gson, and that field never gets emptied on the web service database. Not a good behaviour, by default. Probably more efficient, because it's not sending null records, but it's a surprising result. – Joshua Pinter Nov 27 '17 at 23:44

1 Answers1

28

Try passing it as:

"address2":null,
"address3":null,
"postal_code":"75023"
"country":1,
"state":null

Since you are using Gson converter, try creating the gson as:

Gson gson = new GsonBuilder().serializeNulls().create();

from here.

Community
  • 1
  • 1
Nongthonbam Tonthoi
  • 12,667
  • 7
  • 37
  • 64
  • 14
    I have same solution but another way for apply it.I am posting this comment because this may help someone. You can apply this in retrofit builder like this. `addConverterFactory(GsonConverterFactory.create(new GsonBuilder().serializeNulls().create()))` – Jaydip Kalkani Oct 22 '18 at 04:04
  • 3
    but I want to pass it for some particular request, not for all. then what should I use? – NehaK Jul 20 '21 at 14:42