liveBook · Manning

@CustomSerializer

As explained in Kotlin in Action, 2E

@CustomSerializer is a JKid annotation that associates a property with a custom value serializer.

@CustomSerializer associates a property with a value serializer when default JKid behavior would represent a nonprimitive value as a nested object. The serializer converts between the Kotlin value and its JSON representation. section 12.1.7

Applying a date serializer

data class Person( val name: String, @CustomSerializer(DateSerializer::class) val birthDate: Date ) DateSerializer implements ValueSerializer<Date>, providing toJsonValue and fromJsonValue. The annotation selects it only for birthDate; other properties retain normal serialization. section 12.1.7

The annotation accepts a class reference constrained to ValueSerializer implementations. KClass<out ValueSerializer<*>> permits serializers for different property types while rejecting invalid arguments such as Date::class. section 12.1.7

Reflection discovers the annotation on each KProperty. The serializer class is instantiated through objectInstance or createInstance, then applied to the property value before ordinary JSON serialization; without an annotation, the original value is used. section 12.2.3

interface ValueSerializer<T> {
   fun toJsonValue(value: T): Any?
   fun fromJsonValue(jsonValue: Any?): T
}

ValueSerializer defines the bidirectional conversion contract used by @CustomSerializer. section 12.1.7

annotation class CustomSerializer(
   val serializerClass: KClass<out ValueSerializer<*>>
)

The annotation declaration shows how the generic serializer constraint is expressed as a Kotlin class reference. section 12.1.7

How Kotlin in Action, 2E covers it

How deep it goes
Explains declaration, generic constraints, application, reflective lookup, instantiation, conversion, and fallback behavior.
Examples
Uses a Person.birthDate property with DateSerializer and shows reflective serializer retrieval and property conversion.
What it assumes
Assumes Kotlin annotations, generic types, KClass references, and reflection; teaches the serializer constraint through a concrete annotation design.
What you can do after
Build it from scratch by declaring a constrained annotation, implementing ValueSerializer, applying it to a property, and integrating reflective lookup.
How it connects
Connects annotations with generics, KClass, reflection, ValueSerializer, and JSON serialization.

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.