Kotlin + Gson - How to get an emptyList when null

2019-07-14 04:56发布

问题:

Lets to say I have the following data class:

data class MyDataClass(@SerializedName("myList") val myList: List<String>)

And I try to parse this JSON:

{ "myList": null } or {} 

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?

If I set emptyList() as default value for the constructor. The second JSON works as I want to.

回答1:

Switch your @SerializedName("myList") val myList: List<String> to:

@SerializedName("myList") val myList: List<String>? just to be safe from null.

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