Module serde_yaml::with::singleton_map
source · Expand description
Serialize/deserialize an enum using a YAML map containing one entry in which the key identifies the variant name.
§Example
use serde::{Deserialize, Serialize};
#[derive(Serialize, Deserialize, PartialEq, Debug)]
enum Enum {
Unit,
Newtype(usize),
Tuple(usize, usize),
Struct { value: usize },
}
#[derive(Serialize, Deserialize, PartialEq, Debug)]
struct Struct {
#[serde(with = "serde_yaml::with::singleton_map")]
w: Enum,
#[serde(with = "serde_yaml::with::singleton_map")]
x: Enum,
#[serde(with = "serde_yaml::with::singleton_map")]
y: Enum,
#[serde(with = "serde_yaml::with::singleton_map")]
z: Enum,
}
fn main() {
let object = Struct {
w: Enum::Unit,
x: Enum::Newtype(1),
y: Enum::Tuple(1, 1),
z: Enum::Struct { value: 1 },
};
let yaml = serde_yaml::to_string(&object).unwrap();
print!("{}", yaml);
let deserialized: Struct = serde_yaml::from_str(&yaml).unwrap();
assert_eq!(object, deserialized);
}
The representation using singleton_map
on all the fields is:
w: Unit
x:
Newtype: 1
y:
Tuple:
- 1
- 1
z:
Struct:
value: 1
Without singleton_map
, the default behavior would have been to serialize
as:
w: Unit
x: !Newtype 1
y: !Tuple
- 1
- 1
z: !Struct
value: 1