ValueSerializer<T> defines a conversion boundary between a Kotlin value and its JSON representation. JKid normally writes nonprimitive properties as nested objects; attach a custom serializer when a property needs a different JSON form. The interface supports both directions: toJsonValue converts T to a JSON-compatible value, and fromJsonValue converts that value back to T. section 12.1.7
interface ValueSerializer<T> {
fun toJsonValue(value: T): Any?
fun fromJsonValue(jsonValue: Any?): T
}
The generic type T keeps the Kotlin-side value consistent across serialization and deserialization while allowing the JSON-side value to be Any?. section 12.1.7
Attach a date serializer to one property
Annotate a property with @CustomSerializer(DateSerializer::class). During serialization, JKid obtains the serializer for that property and uses toJsonValue(value); without the annotation, it serializes the original property value. The annotation accepts only classes implementing ValueSerializer, expressed as KClass<out ValueSerializer<*>>. section 12.1.7 section 12.2.3
Serializer lookup handles either a Kotlin object or a regular class. A serializer declared as an object is reused through KClass.objectInstance; otherwise, JKid creates an instance with createInstance(). The retrieved generic serializer is cast for use with the reflected property value. section 12.2.3
The same interface also protects deserialization. A serializer can validate the JSON value and return the exact constructor-parameter type required by callBy(). Built-in serializers can be selected from a KType mapping for values such as Byte, Int, and Boolean; a Boolean serializer rejects a non-Boolean JSON value. section 12.2.5
Use ValueSerializer when a value needs a controlled representation or conversion:
- Implement toJsonValue and fromJsonValue for the Kotlin type being handled. section 12.1.7
- Register a property-specific serializer through @CustomSerializer when its JSON form differs from default nested-object serialization. section 12.1.7
- Use type-based serializers during deserialization to convert JSON values before constructor invocation. section 12.2.5
