Multiple names for JSON field
Asked Answered
S

1

5

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?

Sedgemoor answered 10/10, 2022 at 13:49 Comment(0)
P
13

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.

Plutonium answered 10/10, 2022 at 14:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.