Module serde_yaml::with::singleton_map_recursive
source · Expand description
Apply singleton_map
to all enums contained within the data structure.
§Example
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum Enum {
Int(i32),
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Inner {
a: Enum,
bs: Vec<Enum>,
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Outer {
tagged_style: Inner,
#[serde(with = "serde_yaml::with::singleton_map_recursive")]
singleton_map_style: Inner,
}
fn main() {
let object = Outer {
tagged_style: Inner {
a: Enum::Int(0),
bs: vec![Enum::Int(1)],
},
singleton_map_style: Inner {
a: Enum::Int(2),
bs: vec![Enum::Int(3)],
},
};
let yaml = serde_yaml::to_string(&object).unwrap();
print!("{}", yaml);
let deserialized: Outer = serde_yaml::from_str(&yaml).unwrap();
assert_eq!(object, deserialized);
}
The serialized output is:
tagged_style:
a: !Int 0
bs:
- !Int 1
singleton_map_style:
a:
Int: 2
bs:
- Int: 3
This module can also be used for the top-level serializer or deserializer
call, without serde(with = …)
, as follows.
use std::io::{self, Write};
fn main() {
let object = Inner {
a: Enum::Int(0),
bs: vec![Enum::Int(1)],
};
let mut buf = Vec::new();
let mut serializer = serde_yaml::Serializer::new(&mut buf);
serde_yaml::with::singleton_map_recursive::serialize(&object, &mut serializer).unwrap();
io::stdout().write_all(&buf).unwrap();
let deserializer = serde_yaml::Deserializer::from_slice(&buf);
let deserialized: Inner = serde_yaml::with::singleton_map_recursive::deserialize(deserializer).unwrap();
assert_eq!(object, deserialized);
}