https://kotlinlang.org logo
#serialization
Title
# serialization
r

Rafal

05/31/2023, 2:32 PM
I have a json response which looks kind off like this
Copy code
{
  "questions": [
    {
      "type": "text",
      "dataType": "string",
      "question": "What is your full name?",
      "id": "q1"
    },
    {
      "type": "text",
      "dataType": "integer",
      "question": "How tall are you?",
      "id": "q2"
    },
    {
      "type": "number",
      "question": "What is your age?",
      "id": "q3"
    },
    {
      "type": "single_choice",
      "question": "What is your favorite color?",
      "id": "q4",
      "options": [
        "Red",
        "Blue",
        "Green",
        "Yellow",
        "Other"
      ]
    }
  ]
}
I'd like to have a text type question be polymorphic by the "type" field but also by the "dataType" so the end hierarchy would look like this:
Copy code
interface Question {
    val id: String
    val question: String
}

@Serializable
@SerialName("text")
sealed interface TextQuestion : Question

@Serializable
@SerialName("string")
data class StringTextQuestion(
    override val id: String,
    override val question: String
) : TextQuestion

@Serializable
@SerialName("integer")
data class IntegerTextQuestion(
    override val id: String,
    override val question: String
) : TextQuestion

@Serializable
@SerialName("number")
data class NumberQuestion(
    override val id: String,
    override val question: String
) : Question

@Serializable
@SerialName("single_choice")
data class SingleChoiceQuestion(
    override val id: String,
    override val question: String,
    val options: List<String>
) : Question
is it possible to do using
SerializersModule
?
d

Dominaezzz

06/01/2023, 3:31 PM
Unfortunately this nested polymorphism isn't possible right now