0

I have a parent class RequestFieldResponseBody and two classes that inherit from it (CreateRequestFieldBody and EditRequestFieldBody). I would like to make it so that depending on the child class my id is converted to SerialName("request_field") and @SerialName("issue_field") respectively

@Serializable
internal open class RequestFieldResponseBody(
    open val id: Int,
    @Serializable(with = ValueSerializer::class)
    val value: Value
) {
    @Serializable
    sealed class Value {
        
        // ...
    }
}

@Serializable
internal data class CreateRequestFieldBody(
    @SerialName("request_field")
    override val id: Int,
    val createValue: Value
) : RequestFieldResponseBody(id, createValue)

@Serializable
internal data class EditRequestFieldBody(
    @SerialName("issue_field")
    override val id: Int,
    val editValue: Value
) : RequestFieldResponseBody(id, editValue)

Now when I make a request, this is what I get:

{
  "id": 281,
  "value": [
    5016
  ]
}

Here's what I want to get:

{
   "request_field": 281,
   "value": [
      5016
   ]
}

and

{
   "issue_field": 281,
   "value": [
      5016
   ]
}
1
  • I think you have three choices here as the @SerialName annotation does not work exactly how you would like: (i) make the base class and its fields abstract (which may not be possible), (ii) have the subclasses inherit functionality from the base class by composition (and maybe a shared interface) rather than inheritance, or (iii) write the serializers for these classes by hand, which I think could be done in one class. Commented Dec 27, 2024 at 2:06

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.