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?
CodePudding user response:
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.