• Start

Languages

/

Kotlin

/

Concepts

Serialization

Encode and decode records using kotlinx.serialization with the SurrealDB Kotlin SDK.

The Kotlin SDK uses kotlinx.serialization as its data model. Payloads are sent and received as JSON, so you work with JsonElement values directly, or decode them into your own @Serializable types.

Annotate your data classes with @Serializable. Field names map directly to record fields; use @SerialName to map a different key.

import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable

@Serializable
data class Person(
val name: String,
val age: Int,
@SerialName("created_at") val createdAt: String? = null,
)

The inline .queryAs<T>() helper runs a query and decodes its result into T, while every fluent builder offers the typed .awaitAs<T>() terminal.

import com.surrealdb.kotlin.query.Table
import com.surrealdb.kotlin.query.awaitAs

// Via raw SurrealQL
val people: List<Person> = client.queryAs("SELECT * FROM person")

// Via a builder
val sameAgain: List<Person> = client.select(Table("person")).awaitAs()

To decode an arbitrary JsonElement you already hold, use .decode<T>().

val element = client.query("SELECT * FROM person:ada")
val ada: Person = client.decode(element)

When writing data, build a JsonObject with buildJsonObject, or encode a serializable instance with the client's json instance.

import kotlinx.serialization.json.encodeToJsonElement

val data = client.json.encodeToJsonElement(Person("Ada", 36))
client.create(com.surrealdb.kotlin.query.Table("person")).content(data).await()

The json field on SurrealClientConfig lets you supply a custom Json instance, for example to register contextual serializers or change null handling. The default ignores unknown keys and is lenient.

import kotlinx.serialization.json.Json

val client = SurrealClient(
SurrealClientConfig(
url = "ws://localhost:8000",
json = Json {
ignoreUnknownKeys = true
isLenient = true
explicitNulls = false
},
),
)

Was this page helpful?