3

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",
      ...
   ]
}
inxoy
  • 3,484
  • 2
  • 13
  • 21

1 Answers1

6

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()
inxoy
  • 3,484
  • 2
  • 13
  • 21
Minki
  • 934
  • 5
  • 14