I can use Code 1 to save MutableList to json string using Gson correctly,
But I get the error when I try to restore MutableList
Gson is having a hard time deserialising polymorphic objects as in your MutableList. Here's what you need to do:
Add the RuntimeTypeAdapterFactory.java to your project manually (does not seem to be part of gson library). See also this answer.
Change your code to use the factory
Create Gson instance:
val adapter = RuntimeTypeAdapterFactory
.of(DeviceDef::class.java)
.registerSubtype(BluetoothDef::class.java)
.registerSubtype(WiFiDef::class.java)
val gson = GsonBuilder().setPrettyPrinting().registerTypeAdapterFactory(adapter).create()
register each of your subtypes in the factory and it will work as intended :)