How to register an InstanceCreator with Gson in Kotlin?

后端 未结 1 963
庸人自扰
庸人自扰 2021-01-13 09:50

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

1条回答
  •  失恋的感觉
    2021-01-13 10:19

    Gson is having a hard time deserialising polymorphic objects as in your MutableList. Here's what you need to do:

    1. Add the RuntimeTypeAdapterFactory.java to your project manually (does not seem to be part of gson library). See also this answer.

    2. 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()
      
    3. register each of your subtypes in the factory and it will work as intended :)

    0 讨论(0)
提交回复
热议问题