序列化
Toka 提供对数据序列化和反序列化的内置支持,开箱即用支持 JSON。
JSON 编码
将数据序列化为 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 解码
将 JSON 解析回 Toka 类型:
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 编码
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 编码
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())
}
自定义序列化
为自定义类型实现 @Serialize trait:
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
}
}