I use kotlinx.serialization library to serialize/deserialize JSONs. There is a JSON string:
{"id":"1"}
that can be also represented as
{"uid":"1"}
And I want to handle both names with one property, e.g.:
@Serializable
data class User(val id: String)
Is it possible to parse both JSONs using only one data class and its property?
Yes, you can use the @JsonNames annotation to provide alternative names in addition to the name of the property (see doc). You can also define more than one additional name in the annotation.
@OptIn(ExperimentalSerializationApi::class)
@Serializable
data class User(
@JsonNames("uid")
val id: String,
)
For serialization, the property name will be used. For deserialization, the JSON may contain either the property name or the additional name, both are mapped to the id property.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With