Hey guys, Is it possible to tell retrofit to ignor...
# android
o
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
There is an annotation in Kotlin (keyword in Java) @Transient
o
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
Copy code
@SerializedName("activeSince") var activeSince : Long? = null,
@SerializedName("licenseImageUrl") var licenseImageUrl : String? = null,
Can you try set
null
?
o
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
if value is null I thing gson default to not serializing them
2
j
You can configure if you want to ignore nulls when performing the serialization as Andi mentioned
o
@Javier Troconis Can you please give an example? Where you can configure that?
j
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
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
Thank you @toban!
590 Views