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.
Defining 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,
)Decoding query results
The inline [`.queryAs()`](/docs/reference/kotlin/api/core/surreal-client#query-as) helper runs a query and decodes its result into `T`, while every fluent builder offers the typed [`.awaitAs()`](/docs/reference/kotlin/api/core/query-builder#await-as) 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`](/docs/reference/kotlin/concepts/value-types) you already hold, use [`.decode()`](/docs/reference/kotlin/api/core/surreal-client#decode).
val element = client.query("SELECT * FROM person:ada")
val ada: Person = client.decode(element)Building payloads
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()Customising the JSON format
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
},
),
)Learn more
Value types for
Table,RecordId, and the JSON modelExecuting queries for
queryAsQuery builder reference for
awaitAskotlinx.serialization for the underlying library