0

Why does this work:

val string = "[1, 2, 3]"
val result: ArrayList<Int> = json.decodeFromString(string)

but this doesn't:

@Serializable
class MyClass : ArrayList<Int>()

val string = "[1, 2, 3]"
val myClass: MyClass = json.decodeFromString("string")

throws this error:

Expected start of the object '{', but had 'EOF' instead

MyClass is also an ArrayList so I'm unsure why it doesn't work

TootsieRockNRoll
  • 3,218
  • 2
  • 25
  • 50
  • Serialization framework can't know how to deserialize your custom `MyClass`. `ArrayList` is a specific case that is automatically supported, but any custom class needs a custom way to deserialize it. And `@Serializable` provides serializer that stores objects as maps, not lists. – broot Mar 18 '22 at 18:55
  • Also an ``ArrayList`` isn't a ``MyClass`` so you can't just assign one to a ``MyClass`` variable, in the same way that if a function provides a ``Number`` you can't just assign it to an ``Int`` (but if it provides an ``Int`` you can assign that to a ``Number`` reference). You could make it a ``typealias`` instead of a class though, if your class has nothing else going on in it – cactustictacs Mar 18 '22 at 19:46

0 Answers0