Serialization
Toka provides built-in support for serializing and deserializing data, with JSON support out of the box.
JSON Encoding
Serialize data to JSON:
import stdx/serde/json
import std/io::println
pub shape Person(
name: string,
age: i32,
active: bool
)
fn encode() {
auto person = Person(name = string::from("Alice"), age = 30, active = true)
// auto json_str = json::to_json(person)
// println("{}", json_str) // {"name":"Alice","age":30,"active":true}
}
JSON Decoding
Parse JSON back into Toka types:
import stdx/serde/json
import std/io::println
import core/result::Result
pub shape Person(
name: string,
age: i32,
active: bool
)
fn decode() {
auto data = "{\"name\":\"Bob\",\"age\":25,\"active\":false}"
// auto person_res = json::deserialize_shape<Person>(data)
}
Base64 Encoding
import stdx/encoding/base64
import std/io::println
fn example() {
auto original = "Hello, Toka!"
auto encoded = base64::encode(original.bytes())
println("{}", encoded) // SGVsbG8sIFRva2Eh
auto decoded = base64::decode(encoded.as_str())
}
Hex Encoding
import stdx/encoding/hex
import std/io::println
fn example() {
auto hex_str = hex::encode("Hello".bytes())
println("{}", hex_str) // 48656c6c6f
auto decoded = hex::decode(hex_str.as_str())
}
Custom Serialization
Implement the @Serialize trait for custom types:
import stdx/serde/json::{@ToJson}
pub shape Person(name: string, age: i32, active: bool)
impl Person@ToJson {
pub fn write_json(self, buf#: string) -> string {
buf#.push_str("{\"name\":\"")
buf#.push_str(self.name.as_str())
buf#.push_str("\",\"age\":")
buf#.push_str(string::from_int(self.age).as_str())
buf#.push_str("}")
return buf
}
}