我正在尝试添加自定义注释,以便在调用时将模型中的特定值序列化为 nulltoJSON
来自莫西的方法。我有一些基于此的工作response https://stackoverflow.com/questions/52254876/moshi-custom-qualifier-annotation-to-serialise-null-on-one-property-only但当我有一个嵌套对象时,它对我来说就不够了。
@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)
}
如果我将 null 传递给event
or queries
它们被序列化为:
{
'event': null,
'query': null
}
问题是,当事件不为空时,其中的字段如果为空(例如操作),我不想序列化。我首选的结果是这样的:
{
'event': {
'itemAction': "test"
},
'query': null
}
但我得到的是:
{
'event': {
'action': null,
'itemAction': "test"
},
'query': null
}
以下是基于链接响应的自定义适配器的代码:
@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()
}
}
}
}