Custom Properties
By annotating an extension function with this annotation additional code can be executed as part of the encoding of a @Json-annotated class.
This functionality requires the use of @Json.CodecProvider within the same module. The extension function must use JsonEncoder as receiver type with the same context type as the @Json.CodecProvider-annotated interface or a supertype of that context type.
The annotated extension function must either be a member of the @Json-annotated class or be defined at file-level and take exactly one value parameter of the @Json-annotated class.
Note that the function can have any name, its return value is ignored, it must have internal or public visibility, and it must not be generic.
Example
Class member
class User(
// …
val emailAddress: String
) {
@Json.CustomProperties
fun JsonEncoder<AuthenticationAwareContext>.writeCustomProperties() {
if (this == context.authenticatedUser) {
writeMapElement("emailAddress", emailAddress)
}
}
}Content copied to clipboard
File-level extension function
@Json.CustomProperties
fun JsonEncoder<AuthenticationAwareContext>.writeCustomProperties(user: User) {
if (user == context.authenticatedUser) {
writeMapElement("emailAddress", user.emailAddress)
}
}Content copied to clipboard