2

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.

crgarridos
  • 8,758
  • 3
  • 49
  • 61
  • It's theoretically possible whatever library/framework you use uses reflection, and therefore bypasses the constructor, and sets the values directly. – Zoe Oct 02 '18 at 16:16
  • Yes I'm aware of that, but I would find a way to set null list as empty by default – crgarridos Oct 03 '18 at 06:56
  • Without a `TypeAdapter`, I cannot think of any way. Maybe something with `Gson.Builder.serializeNulls`. You should try anyway with a `TypeAdapter` first IMO. – shkschneider Jun 19 '19 at 13:16

1 Answers1

2

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())
coroutineDispatcher
  • 7,718
  • 6
  • 30
  • 58