Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple names for JSON field

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?

like image 714
Sergey Avatar asked Jul 16 '26 23:07

Sergey


1 Answers

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.

like image 145
Joffrey Avatar answered Jul 20 '26 23:07

Joffrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!