I mean how to serialize some property into null va...
# squarelibraries
p
I mean how to serialize some property into null value
i
add a
?
to the type
Copy code
data class Assets(@Json(name = "asset") val assetList: List<Asset>?)
p
it deserialises to null but not serializes back
i
try it with
asLenient()
Copy code
.addConverterFactory(MoshiConverterFactory.create(moshi).asLenient())
it alsoi has a
withNullSerialization()
method
p
The solution was to added annotaiton to each property I want to keep null in json:
@Retention(AnnotationRetention.RUNTIME) @JsonQualifier annotation class SerializeNulls { companion object { val JSON_ADAPTER_FACTORY: JsonAdapter.Factory = object : JsonAdapter.Factory { override fun create(type: Type, annotations: Set<Annotation>, moshi: Moshi): JsonAdapter<*>? { val nextAnnotations = Types.nextAnnotations(annotations, SerializeNulls::class.java) ?: return null return moshi.nextAdapter<Any>(this, type, nextAnnotations).serializeNulls() } } } }
👍 1
e
yep. the JsonQualifier the way to go for having conditional serialization of nulls. https://stackoverflow.com/a/52265735