0
# Annotations
1
2
Essential annotations for controlling serialization behavior in kotlinx.serialization. These annotations allow you to mark classes as serializable, customize field names, control which properties are serialized, and configure advanced serialization features.
3
4
## Capabilities
5
6
### Core Annotations
7
8
The fundamental annotations needed for basic serialization.
9
10
```kotlin { .api }
11
/**
12
* Marks a class as serializable, instructing the compiler plugin to generate a KSerializer implementation.
13
* @param with Optional custom serializer class to use instead of generated one
14
*/
15
@Target(AnnotationTarget.CLASS, AnnotationTarget.PROPERTY, AnnotationTarget.TYPE)
16
annotation class Serializable(val with: KClass<out KSerializer<*>> = KSerializer::class)
17
18
/**
19
* Overrides the name of a class or property in the SerialDescriptor.
20
* Used to customize how fields appear in the serialized format.
21
* @param value The custom name to use in serialization
22
*/
23
@Target(AnnotationTarget.CLASS, AnnotationTarget.PROPERTY)
24
annotation class SerialName(val value: String)
25
26
/**
27
* Marks a property as invisible to the entire serialization process.
28
* Transient properties are completely ignored during serialization and deserialization.
29
*/
30
@Target(AnnotationTarget.PROPERTY)
31
annotation class Transient
32
```
33
34
**Usage Examples:**
35
36
```kotlin
37
@Serializable
38
data class User(
39
@SerialName("user_name")
40
val name: String,
41
val email: String,
42
@Transient
43
val password: String = ""
44
)
45
46
// Serializes as: {"user_name":"Alice","email":"alice@example.com"}
47
// password field is completely ignored
48
```
49
50
### Property Control Annotations
51
52
Annotations for fine-grained control over property serialization behavior.
53
54
```kotlin { .api }
55
/**
56
* Marks a property as required during deserialization, even if it has a default value.
57
* Throws MissingFieldException if the field is not present in input.
58
*/
59
@Target(AnnotationTarget.PROPERTY)
60
annotation class Required
61
62
/**
63
* Controls whether a property is serialized when its value equals the default value.
64
* @param mode Strategy for encoding default values
65
*/
66
@Target(AnnotationTarget.PROPERTY)
67
annotation class EncodeDefault(val mode: Mode = Mode.ALWAYS) {
68
enum class Mode {
69
/**
70
* Configures serializer to always encode the property, even if its value is equal to its default.
71
* For annotated properties, format settings are not taken into account.
72
*/
73
ALWAYS,
74
75
/**
76
* Configures serializer not to encode the property if its value is equal to its default.
77
* For annotated properties, format settings are not taken into account.
78
*/
79
NEVER
80
}
81
}
82
```
83
84
**Usage Examples:**
85
86
```kotlin
87
@Serializable
88
data class Config(
89
@Required
90
val apiKey: String = "", // Always required, even with default
91
92
@EncodeDefault(EncodeDefault.Mode.ALWAYS)
93
val timeout: Int = 30, // Always serialized, even if 30
94
95
@EncodeDefault(EncodeDefault.Mode.NEVER)
96
val debug: Boolean = false // Only serialized if true
97
)
98
```
99
100
### Custom Serializer Annotations
101
102
Annotations for specifying and managing custom serializers.
103
104
```kotlin { .api }
105
/**
106
* Instructs the plugin to turn the annotated class into a serializer for the specified target class.
107
* @param forClass The class this serializer handles
108
*/
109
@Target(AnnotationTarget.CLASS)
110
annotation class Serializer(val forClass: KClass<*>)
111
112
/**
113
* Instructs the plugin to use ContextualSerializer for the annotated property.
114
* The actual serializer is resolved from SerializersModule at runtime.
115
*/
116
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.TYPE)
117
annotation class Contextual
118
119
/**
120
* Keep the auto-generated KSerializer even when a custom serializer is specified.
121
* The generated serializer is available via generatedSerializer() function.
122
*/
123
@Target(AnnotationTarget.CLASS)
124
annotation class KeepGeneratedSerializer
125
```
126
127
**Usage Examples:**
128
129
```kotlin
130
@Serializer(forClass = LocalDate::class)
131
object LocalDateSerializer : KSerializer<LocalDate> {
132
override val descriptor = PrimitiveSerialDescriptor("LocalDate", PrimitiveKind.STRING)
133
override fun serialize(encoder: Encoder, value: LocalDate) = encoder.encodeString(value.toString())
134
override fun deserialize(decoder: Decoder): LocalDate = LocalDate.parse(decoder.decodeString())
135
}
136
137
@Serializable
138
data class Event(
139
val name: String,
140
@Contextual
141
val date: LocalDate // Resolved from SerializersModule
142
)
143
```
144
145
### File-Level Configuration Annotations
146
147
Annotations that apply to entire files or modules for bulk configuration.
148
149
```kotlin { .api }
150
/**
151
* Use ContextualSerializer for every type listed in forClasses within the annotated file.
152
* @param forClasses Array of classes to treat as contextual
153
*/
154
@Target(AnnotationTarget.FILE)
155
annotation class UseContextualSerialization(vararg val forClasses: KClass<*>)
156
157
/**
158
* Adds the specified serializer classes to the serialization resolution process for the file.
159
* @param serializerClasses Array of serializer classes to register
160
*/
161
@Target(AnnotationTarget.FILE)
162
annotation class UseSerializers(vararg val serializerClasses: KClass<out KSerializer<*>>)
163
164
/**
165
* Instructs the plugin to use PolymorphicSerializer for the annotated property or type.
166
* Used for polymorphic serialization scenarios.
167
*/
168
@Target(AnnotationTarget.PROPERTY, AnnotationTarget.CLASS, AnnotationTarget.TYPE)
169
annotation class Polymorphic
170
```
171
172
**Usage Examples:**
173
174
```kotlin
175
@file:UseContextualSerialization(LocalDate::class, UUID::class)
176
@file:UseSerializers(LocalDateSerializer::class, UUIDSerializer::class)
177
178
package com.example.models
179
180
@Serializable
181
data class Document(
182
val id: UUID, // Uses UUIDSerializer from file-level config
183
val created: LocalDate // Uses LocalDateSerializer from file-level config
184
)
185
```
186
187
### Meta-Annotations
188
189
Annotations for creating custom serialization annotations.
190
191
```kotlin { .api }
192
/**
193
* Meta-annotation for creating custom serialization-specific annotations.
194
* Marks an annotation as containing serialization metadata.
195
*/
196
@Target(AnnotationTarget.ANNOTATION_CLASS)
197
annotation class SerialInfo
198
199
/**
200
* Like SerialInfo but makes the annotation inheritable by subclasses.
201
* Useful for creating annotation hierarchies.
202
*/
203
@Target(AnnotationTarget.ANNOTATION_CLASS)
204
annotation class InheritableSerialInfo
205
206
/**
207
* Meta-annotation that adds Serializable behavior to user-defined annotations.
208
* Classes annotated with meta-serializable annotations become serializable.
209
*/
210
@Target(AnnotationTarget.ANNOTATION_CLASS)
211
annotation class MetaSerializable
212
```
213
214
**Usage Examples:**
215
216
```kotlin
217
@SerialInfo
218
@Target(AnnotationTarget.PROPERTY)
219
annotation class Since(val version: String)
220
221
@InheritableSerialInfo
222
@Target(AnnotationTarget.CLASS)
223
annotation class ApiVersion(val version: Int)
224
225
@MetaSerializable
226
@Target(AnnotationTarget.CLASS)
227
annotation class JsonSerializable
228
229
// Classes with JsonSerializable automatically become @Serializable
230
@JsonSerializable
231
data class User(
232
@Since("1.0")
233
val name: String,
234
@Since("1.1")
235
val email: String
236
)
237
```
238
239
## Error Handling
240
241
Annotation-related errors typically occur at compile time when the kotlinx.serialization compiler plugin processes the annotations. Common issues include:
242
243
- Missing `@Serializable` annotation on classes used in serializable properties
244
- Invalid `@SerialName` values that conflict with other field names
245
- Incorrect `@Serializer` configurations pointing to non-existent classes
246
- Circular dependencies in `@Contextual` or polymorphic type hierarchies