(反)序列化 Rust 对象的事实上的标准方法是serde https://crates.io/crates/serde。给定一个 Rust 结构(或枚举),它会生成一个中间表示,然后可以将其转换为所需的格式(例如 json)。给定一个结构:
use serde::{Serialize, Deserialize};
// here the "magic" conversion is generated
#[derive(Debug, Serialize, Deserialize)]
struct T {
i: i32,
f: f64,
}
您可以使用简单的 oneliner 获得 json 表示形式:
let t = T { i: 1, f: 321.456 };
println!("{}", serde_json::to_string(&t).unwrap());
// prints `{"i":1,"f":321.456}`
以及转换回来:
let t: T = serde_json::from_str(r#"{"i":1,"f":321.456}"#).unwrap();
println!("i: {}, f: {}", t.i, t.f);
// prints i: 1, f: 321.456
是游乐场链接。这是一个例子serde_json https://crates.io/crates/serde_json用法,但您可能会找到其他更合适的库,例如serde_cbor https://crates.io/crates/serde_cbor, serde_yaml https://crates.io/crates/serde_yaml, bincode https://crates.io/crates/bincode, serde_xml https://crates.io/crates/serde_xml还有很多很多其他的。