问题描述
可以说我具有以下数据类:
Lets to say I have the following data class:
data class MyDataClass(@SerializedName("myList") val myList: List<String>)
然后我尝试解析此JSON:
And I try to parse this JSON:
{ "myList": null } or {}
我想得到一个空列表,但我得到一个空的myList
.有人知道如何在不为包含列表的每种类型实现registerTypeAdapter
的情况下进行序列化吗?
I want to get an empty list but I get a null myList
. Does anyone know how to serialize this without implementing a registerTypeAdapter
for each type containing a list?
如果我将emptyList()
设置为构造函数的默认值.第二个JSON如我所愿.
If I set emptyList()
as default value for the constructor. The second JSON works as I want to.
推荐答案
将您的@SerializedName("myList") val myList: List<String>
切换为:
@SerializedName("myList") val myList: List<String>?
只是为了安全起见null
.
现在,Kotlin具有默认参数.但我不知道它是否适合您的情况:
Now, Kotlin has default parameters. But I don't know if it fits your case:
data class MyDataClass(@SerializedName("myList") val myList: List<String> = emptyList())
这篇关于Kotlin + Gson-如何在数据类为null时获取EmptyList的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!