I'm trying to use PolymorphicJsonAdapterFactory in order to obtain different types, but am always getting odd exception:
Missing label for test_type
My entity:
@JsonClass(generateAdapter = true)
data class TestResult(
@Json(name = "test_type") val testType: TestType,
...
@Json(name = "session") val session: Session,
...
)
Here is my moshi factory:
val moshiFactory = Moshi.Builder()
.add(
PolymorphicJsonAdapterFactory.of(Session::class.java, "test_type")
.withSubtype(FirstSession::class.java, "first")
.withSubtype(SecondSession::class.java, "second")
)
.build()
Structure of json response:
{
response: [
test_type: "first",
...
]
}
test_type must be a field of session class.
if the test_type can't be inside a session class, then you must declare a class for every variant of TestResult containing the specific Session class as follows:
sealed class TestResultSession(open val testType: String)
@JsonClass(generateAdapter = true)
data class TestResultFirstSession(
@Json(name = "test_type") override val testType: String,
@Json(name = "session") val session: FirstSession
) : TestResultSession(testType)
@JsonClass(generateAdapter = true)
data class TestResultSecondSession(
@Json(name = "test_type") override val testType: String,
@Json(name = "session") val session: SecondSession
) : TestResultSession(testType)
and your moshi polymorphic adapter:
val moshiFactory = Moshi.Builder()
.add(
PolymorphicJsonAdapterFactory.of(TestResultSession::class.java,"test_type")
.withSubtype(TestResultFirstSession::class.java, "first")
.withSubtype(TestResultSecondSession::class.java, "second")
)
.build()
it is always good practise to provide a fallback, so your deserialisation doesn't fail, in case test_type is unknown:
@JsonClass(generateAdapter = true)
data class FallbackTestResult(override val testType: String = "") : TestResultSession(testType)
val moshiFactory = Moshi.Builder()
.add(
PolymorphicJsonAdapterFactory.of(TestResultSession::class.java,"test_type")
.withSubtype(TestResultFirstSession::class.java, "first")
.withSubtype(TestResultSecondSession::class.java, "second")
.withDefaultValue(FallbackTestResult())
)
.build()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With