https://kotlinlang.org logo
#android
Title
# android
o

Ofir Bar

02/19/2020, 12:40 PM
Hey guys, Is it possible to tell retrofit to ignore certain fields of an object when sending the object over the network? We have a request object
Profession
that we send to our backend using Retrofit.
Copy code
data class Profession (
	@SerializedName("activeSince") var activeSince : Long?,
	@SerializedName("name") var businessName : String?,
	@SerializedName("description") var businessDescription : String?,
	@SerializedName("licenseImageUrl") var licenseImageUrl : String?
)
Sometimes we send the entire object, but other times, I prefer to only send specific fields (for example, only the
businessDescription
and
businessName
). Is it possible to tell retrofit to not include the other 2 fields in the network request? (
activeSince
and
licenseImageUrl
). Note: I can’t send
activeSince
and
licenseImageUrl
as null. Our backend will send me back errors if I attempt to do that (edited)
o

Oscar Sequeiros

02/19/2020, 12:48 PM
There is an annotation in Kotlin (keyword in Java) @Transient
o

Ofir Bar

02/19/2020, 1:05 PM
Using Transient will cause me to always not serialize/deserealize a field. I want to have the option to sometimes serialize it and sometimes not. Is it possible?
d

dino9

02/19/2020, 1:07 PM
Copy code
@SerializedName("activeSince") var activeSince : Long? = null,
@SerializedName("licenseImageUrl") var licenseImageUrl : String? = null,
Can you try set
null
?
o

Ofir Bar

02/19/2020, 1:31 PM
I can, but the backend does not allow receiving null values. Is there a way to not include the field in JSON at all?
a

Andi Beqiri

02/19/2020, 1:33 PM
if value is null I thing gson default to not serializing them
2
j

Javier Troconis

02/19/2020, 2:37 PM
You can configure if you want to ignore nulls when performing the serialization as Andi mentioned
o

Ofir Bar

02/19/2020, 2:41 PM
@Javier Troconis Can you please give an example? Where you can configure that?
j

Javier Troconis

02/19/2020, 2:45 PM
Using the GsonBuilder, but as it has been said the default behavior is to ignore null (which seems to be what you want). If you wanted to include nulls you would have to use
serializeNulls()
on the builder
t

toban

02/19/2020, 3:54 PM
I looked for this as well and found https://github.com/Kotlin/kotlinx.serialization/issues/195. As proposed in that thread, a possible workaround is to set
encodeDefaults = false
in your JsonCofiguration.
o

Ofir Bar

02/19/2020, 4:06 PM
Thank you @toban!
375 Views