Skip to content

Serde

Course: Rust for Solana contracts - chapter 23

Serde is a popular serialization and deserialization framework in Rust. It provides a way to convert Rust data structures into different formats (serialization) and vice versa (deserialization). The most common use cases involve working with formats like JSON, YAML, TOML, and others.

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
use serde::{Serialize, Deserialize};
use serde_json::{self, Value};
#[derive(Serialize, Deserialize, Debug)]
struct Person {
name: String,
age: u32,
}
fn main() {
let person = Person {
name: String::from("John Doe"),
age: 30,
};
// Serialize to JSON
let json_str = serde_json::to_string(&person).unwrap();
println!("Serialized JSON: {}", json_str);
// Deserialize from JSON
let deserialized_person: Person = serde_json::from_str(&json_str).unwrap();
println!("Deserialized Person: {:?}", deserialized_person);
}
Serialize to Yaml
use serde::{Deserialize as DeserializeSerde, Serialize as SerializeSerde};
#[derive(SerializeSerde, DeserializeSerde, Debug, PartialEq)]
struct User {
username: String,
password: String
}
#[derive(Debug, PartialEq, SerializeSerde, DeserializeSerde)]
struct MyStruct {
id: u64,
data: String,
v: Vec<u32>,
user: User
}
fn main() {
let s = MyStruct {
id: 32,
data: String::from("Harkirtat"),
v: vec![1, 2, 3],
user: User {
username: String::from("Harkirtat"),
password: String::from("Singh")
}
};
let json_str = serde_yaml::to_string(&s).unwrap();
print!("{}", json_str);
let deserialized: MyStruct = serde_yaml::from_str(&json_str).unwrap();
assert_eq!(deserialized, s);
println!("done!")
}
Change variables to uppercase/camelcase using macros
Create a github workflow serializer/deseralizer that you can use to define/create CI/CD files in rust and serialise them to yml (no solution)