rhai/examples/serde.rs

77 lines
1.8 KiB
Rust
Raw Normal View History

2020-07-04 16:32:18 +02:00
#[cfg(not(feature = "serde"))]
fn main() {
2020-07-04 16:52:45 +02:00
println!(r#"This example requires the "serde" feature which is not enabled by default."#);
println!("Try: cargo run --features serde --example serde");
2020-07-04 16:32:18 +02:00
}
#[cfg(feature = "serde")]
fn main() {
example::ser();
println!();
example::de();
}
#[cfg(feature = "serde")]
mod example {
use rhai::{de::from_dynamic, ser::to_dynamic};
use rhai::{Dynamic, Engine, Map};
2020-07-04 16:52:45 +02:00
use serde::{Deserialize, Serialize};
2020-07-04 16:32:18 +02:00
2020-07-04 16:52:45 +02:00
#[derive(Debug, Serialize, Deserialize)]
2020-07-04 16:32:18 +02:00
struct Point {
x: f64,
y: f64,
}
2020-07-04 16:52:45 +02:00
#[derive(Debug, Serialize, Deserialize)]
2020-07-04 16:32:18 +02:00
struct MyStruct {
a: i64,
b: Vec<String>,
c: bool,
d: Point,
}
pub fn ser() {
let x = MyStruct {
a: 42,
b: vec!["hello".into(), "world".into()],
c: true,
d: Point {
x: 123.456,
y: 999.0,
},
};
println!("Source struct: {:#?}", x);
// Convert the 'MyStruct' into a 'Dynamic'
let map: Dynamic = to_dynamic(x).unwrap();
assert!(map.is::<Map>());
println!("Serialized to Dynamic: {:#?}", map);
}
pub fn de() {
let engine = Engine::new();
let result: Dynamic = engine
.eval(
r#"
2020-10-07 09:51:00 +02:00
#{
2020-07-04 16:32:18 +02:00
a: 42,
b: [ "hello", "world" ],
c: true,
d: #{ x: 123.456, y: 999.0 }
}
"#,
)
.unwrap();
println!("Source Dynamic: {:#?}", result);
// Convert the 'Dynamic' object map into 'MyStruct'
let x: MyStruct = from_dynamic(&result).unwrap();
println!("Deserialized to struct: {:#?}", x);
}
}