or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations.mdbuiltins.mddescriptors.mdencoding.mdindex.mdmodules.mdserializers.md

index.mddocs/

0

# kotlinx.serialization-core-js

1

2

A powerful Kotlin multiplatform serialization library compiled for JavaScript that provides comprehensive type-safe serialization and deserialization capabilities for JavaScript/TypeScript applications.

3

4

## Package Information

5

6

**Maven Package:** `org.jetbrains.kotlinx:kotlinx-serialization-core-js`

7

**Platform:** Kotlin/JS

8

**Language Support:** JavaScript, TypeScript

9

**API Level:** Kotlin Serialization 1.6+

10

11

### Installation

12

13

For Kotlin/JS projects, add to your `build.gradle.kts`:

14

15

```kotlin

16

dependencies {

17

implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:1.9.0")

18

}

19

```

20

21

Or for Gradle with Groovy:

22

23

```gradle

24

dependencies {

25

implementation 'org.jetbrains.kotlinx:kotlinx-serialization-core:1.9.0'

26

}

27

```

28

29

### Core Imports

30

31

```kotlin

32

// Core serialization APIs

33

import kotlinx.serialization.*

34

import kotlinx.serialization.builtins.*

35

import kotlinx.serialization.descriptors.*

36

import kotlinx.serialization.encoding.*

37

import kotlinx.serialization.modules.*

38

39

```

40

41

## Basic Usage

42

43

### Simple Data Class Serialization

44

45

```kotlin

46

// Define a serializable data class

47

@Serializable

48

data class User(val name: String, val age: Int, val email: String)

49

50

// Create an instance

51

val user = User("John Doe", 30, "john@example.com")

52

53

// Get the serializer (requires a format like JSON)

54

val serializer = User.serializer()

55

56

// Usage with a format implementation (e.g., kotlinx-serialization-json):

57

// val json = Json.encodeToString(serializer, user)

58

// val deserializedUser = Json.decodeFromString(serializer, json)

59

```

60

61

### Custom Property Names

62

63

```kotlin

64

@Serializable

65

data class ApiResponse(

66

@SerialName("user_id") val userId: Int,

67

@SerialName("full_name") val fullName: String

68

)

69

```

70

71

### Optional and Required Fields

72

73

```kotlin

74

@Serializable

75

data class Profile(

76

@Required val username: String, // Must be present during deserialization

77

val bio: String = "", // Optional with default value

78

@Transient val temporaryData: String? = null // Excluded from serialization

79

)

80

```

81

82

## Architecture

83

84

The kotlinx.serialization-core-js library is built around several key architectural components:

85

86

### Core Interfaces

87

88

```typescript

89

interface KSerializer<T> extends SerializationStrategy<T>, DeserializationStrategy<T> {

90

readonly descriptor: SerialDescriptor;

91

}

92

93

interface SerializationStrategy<T> {

94

serialize(encoder: Encoder, value: T): void;

95

}

96

97

interface DeserializationStrategy<T> {

98

deserialize(decoder: Decoder): T;

99

}

100

```

101

102

### Descriptor System

103

104

Every serializable type has an associated `SerialDescriptor` that describes its structure:

105

106

- **Serial Name**: Identifies the type in serialized form

107

- **Kind**: Categorizes the type (primitive, class, list, map, etc.)

108

- **Elements**: For structured types, describes each property/element

109

- **Annotations**: Metadata attached to the type or its elements

110

111

### Format Independence

112

113

The library separates serialization logic from format-specific encoding:

114

115

1. **Serializers** define *what* to serialize

116

2. **Encoders/Decoders** define *how* to represent data in specific formats

117

3. **Formats** coordinate between serializers and encoders/decoders

118

119

This architecture enables the same serializable classes to work with JSON, ProtoBuf, CBOR, and other formats.

120

121

## Capabilities

122

123

### Annotations

124

125

Comprehensive annotation system for controlling serialization behavior:

126

127

```kotlin

128

@Serializable // Mark classes as serializable

129

@SerialName("custom") // Override property/class names

130

@Required // Require fields during deserialization

131

@Transient // Exclude fields from serialization

132

@Contextual // Use contextual serializer lookup

133

@Polymorphic // Enable polymorphic serialization

134

```

135

136

**[Complete Annotations Reference](./annotations.md)**

137

138

### Core Serializers

139

140

Built-in and factory serializers for all standard types:

141

142

```kotlin

143

// Retrieve serializers

144

serializer<String>() // For reified types

145

String.serializer() // Via companion object

146

ListSerializer(Int.serializer()) // Collection serializers

147

```

148

149

**[Serializers API Reference](./serializers.md)**

150

151

### Type Descriptors

152

153

Introspect and describe serializable type structure:

154

155

```kotlin

156

val descriptor = User.serializer().descriptor

157

println(descriptor.serialName) // "User"

158

println(descriptor.kind) // StructureKind.CLASS

159

println(descriptor.elementsCount) // 3

160

```

161

162

**[Descriptors API Reference](./descriptors.md)**

163

164

### Encoding/Decoding

165

166

Low-level APIs for format implementors:

167

168

```kotlin

169

interface Encoder {

170

fun encodeString(value: String)

171

fun encodeInt(value: Int)

172

fun beginStructure(descriptor: SerialDescriptor): CompositeEncoder

173

}

174

```

175

176

**[Encoding/Decoding Reference](./encoding.md)**

177

178

### Built-in Type Support

179

180

Comprehensive serializers for Kotlin standard library types:

181

182

```kotlin

183

// Primitives and standard types

184

String.serializer()

185

Int.serializer()

186

Duration.serializer()

187

188

// Collections

189

ListSerializer(String.serializer())

190

MapSerializer(String.serializer(), Int.serializer())

191

192

// Arrays

193

IntArraySerializer()

194

ArraySerializer(String.serializer())

195

```

196

197

**[Built-in Serializers Reference](./builtins.md)**

198

199

### Runtime Configuration

200

201

Flexible module system for contextual and polymorphic serialization:

202

203

```kotlin

204

val module = SerializersModule {

205

contextual(LocalDateTime::class, LocalDateTimeSerializer)

206

polymorphic(Animal::class) {

207

subclass(Cat::class)

208

subclass(Dog::class)

209

}

210

}

211

```

212

213

**[Modules and Configuration](./modules.md)**

214

215

## JavaScript Integration

216

217

### Long Value Handling

218

219

For JavaScript compatibility, use `LongAsStringSerializer` to avoid precision issues:

220

221

```typescript

222

@Serializable

223

class TransactionRecord {

224

@Serializable(LongAsStringSerializer::class)

225

amount: string; // Serialized as string to preserve precision

226

227

constructor(amount: string) {

228

this.amount = amount;

229

}

230

}

231

```

232

233

### TypeScript Type Definitions

234

235

The library provides comprehensive TypeScript definitions:

236

237

```typescript

238

// Serializer functions are typed

239

const userSerializer: KSerializer<User> = User.serializer();

240

241

// Generic serializers maintain type safety

242

const listSerializer: KSerializer<Array<string>> = ListSerializer(String.serializer());

243

244

// Format operations are fully typed

245

const users: Array<User> = format.decodeFromString(listSerializer, jsonString);

246

```

247

248

### Platform-Specific Considerations

249

250

- Enum classes require `@Serializable` annotation on JavaScript

251

- Interface detection uses JavaScript-specific metadata

252

- Type lookup leverages JavaScript's dynamic features

253

- All primitive arrays and reference arrays are supported

254

255

## Error Handling

256

257

The library provides specific exception types for different error conditions:

258

259

```typescript

260

try {

261

const result = format.decodeFromString(serializer, invalidJson);

262

} catch (e) {

263

if (e instanceof SerializationException) {

264

console.log("Serialization error:", e.message);

265

} else if (e instanceof MissingFieldException) {

266

console.log("Missing required field:", e.missingFields);

267

}

268

}

269

```

270

271

## Format Integration

272

273

While kotlinx.serialization-core-js provides the serialization framework, it's designed to work with format-specific libraries:

274

275

```typescript

276

// JSON format (separate library)

277

import { Json } from 'kotlinx-serialization-json-js';

278

279

const json = Json.Default;

280

const serialized = json.encodeToString(User.serializer(), user);

281

const deserialized = json.decodeFromString(User.serializer(), serialized);

282

283

// Other formats follow similar patterns

284

import { ProtoBuf } from 'kotlinx-serialization-protobuf-js';

285

import { Cbor } from 'kotlinx-serialization-cbor-js';

286

```

287

288

This modular approach allows you to include only the formats your application needs while sharing the same serializable class definitions across all formats.