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
]
}
@SerialNameannotation 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.