I am attempting to add a custom annotation to serialize specific values in my model to null when calling the toJSON
method from Moshi. I have something working based on this response but it's falling short for me when I have a nested object.
@JsonClass(generateAdapter = true)
data class EventWrapper(
@SerializeNulls val event: Event?,
@SerializeNulls val queries: Queries? = null) {
@JsonClass(generateAdapter = true)
data class Queries(val stub: String?)
@JsonClass(generateAdapter = true)
data class Event(
val action: String?,
val itemAction: String)
}
If I pass null to event
or queries
they are serialized as:
{
'event': null,
'query': null
}
The issue is when event isn't null there are fields inside of it I would like to not serialize if they are null such as action. My preferred result would be this:
{
'event': {
'itemAction': "test"
},
'query': null
}
But instead I am getting:
{
'event': {
'action': null,
'itemAction': "test"
},
'query': null
}
Here is the code for my custom adapter based on the linked response:
@Retention(RetentionPolicy.RUNTIME)
@JsonQualifier
annotation class SerializeNulls {
companion object {
var JSON_ADAPTER_FACTORY: JsonAdapter.Factory = object : JsonAdapter.Factory {
@RequiresApi(api = Build.VERSION_CODES.P)
override fun create(type: Type, annotations: Set<Annotation?>, moshi: Moshi): JsonAdapter<*>? {
val nextAnnotations = Types.nextAnnotations(annotations, SerializeNulls::class.java)
return if (nextAnnotations == null) {
null
} else {
moshi.nextAdapter<Any>(this, type, nextAnnotations).serializeNulls()
}
}
}
}