【发布时间】:2019-01-20 21:12:48
【问题描述】:
问题类似于this
但不同之处在于 type 不包含在被反序列化的 JSON 对象中,而是包含在外部级别(根)中。
像这样:
{
"type": "A",
"myObject" : { <- type is NOT stored in here
...
}
}
目的是将这个JSON对象映射到Blah
// Code is in Kotlin
interface Foo {
...
}
class Bar : Foo { // Map to this if 'type' is A
...
}
class Baz : Foo { // Map to this if 'type' is B
...
}
class Blah {
val type : String? = null
val myObject : Foo? = null
}
如果type 是A 和Baz 如果type 是B,我如何使myObject 映射到Bar?
我暂时求助于手动读取根 JSON 对象。任何帮助将非常感激。谢谢。
编辑:
当尝试使用 Gson fromJson 方法将根 JSON 对象映射到 Blah 时,我收到此错误:Unable to invoke no-args constructor for class Foo。 - 但这无论如何都是不正确的,因为我需要 myObject 专门映射到 Baz 或 Bar。
【问题讨论】:
标签: java android kotlin gson deserialization