带数据的 Kotlin Gson 类
Kotlin Gson with Data Classes
正在尝试使用 Gson 解析复杂的 json 对象。以下是失败的数据 classes:
data class Advisor(
val students: List<Student>?,
)
sealed class Student {
data class BusinessMajor(val name: String, val items: List<Courses>) : Student()
data class ArtsMajor(val name: String, val items: List<Courses>) : Student()
}
在运行时,我得到这个异常:
java.lang.RuntimeException: Failed to invoke private
com.mysite.myapp.ApiResponse$Student() with no args
我读到这可以通过尝试解析抽象 classes 来创建,但我读过的所有帖子都是针对 Java 的。我没有看到任何对 Kotlin 数据 classes 有帮助的东西,特别是用 sealed
class.
感谢任何帮助。谢谢
密封类型 类 无法实例化:see here
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
Sealed classes are not allowed to have non-private constructors (their constructors are private by default).
它应该和 Java 中的一样工作。改编 中的示例:
val rta = RuntimeTypeAdapterFactory.of(Student::class.java)
.registerSubtype(Student.BusinessMajor::class.java)
.registerSubtype(Student.ArtsMajor::class.java)
val gson = new GsonBuilder()
.registerTypeAdapterFactory(rta)
.create()
但是:
这样你需要为每个密封的class写一个工厂。也许有一个帮助库可以避免这个问题,但如果是的话我还没有找到。
另见
总的来说,我会强烈考虑使用 Moshi 或其他支持 Kotlin 的 JSON 库。
正在尝试使用 Gson 解析复杂的 json 对象。以下是失败的数据 classes:
data class Advisor(
val students: List<Student>?,
)
sealed class Student {
data class BusinessMajor(val name: String, val items: List<Courses>) : Student()
data class ArtsMajor(val name: String, val items: List<Courses>) : Student()
}
在运行时,我得到这个异常:
java.lang.RuntimeException: Failed to invoke private com.mysite.myapp.ApiResponse$Student() with no args
我读到这可以通过尝试解析抽象 classes 来创建,但我读过的所有帖子都是针对 Java 的。我没有看到任何对 Kotlin 数据 classes 有帮助的东西,特别是用 sealed
class.
感谢任何帮助。谢谢
密封类型 类 无法实例化:see here
A sealed class is abstract by itself, it cannot be instantiated directly and can have abstract members.
Sealed classes are not allowed to have non-private constructors (their constructors are private by default).
它应该和 Java 中的一样工作。改编 中的示例:
val rta = RuntimeTypeAdapterFactory.of(Student::class.java)
.registerSubtype(Student.BusinessMajor::class.java)
.registerSubtype(Student.ArtsMajor::class.java)
val gson = new GsonBuilder()
.registerTypeAdapterFactory(rta)
.create()
但是:
这样你需要为每个密封的class写一个工厂。也许有一个帮助库可以避免这个问题,但如果是的话我还没有找到。
另见
总的来说,我会强烈考虑使用 Moshi 或其他支持 Kotlin 的 JSON 库。