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()