1 | //! An example of implementing `serde::Serialize` and `serde::Deserialize`. |
2 | //! The `#[serde(transparent)]` attribute is recommended to serialize directly |
3 | //! to the underlying bits type without wrapping it in a `serde` newtype. |
4 | |
5 | #[cfg (feature = "serde" )] |
6 | fn main() { |
7 | use serde_derive::*; |
8 | |
9 | bitflags::bitflags! { |
10 | #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] |
11 | #[serde(transparent)] |
12 | pub struct Flags: u32 { |
13 | const A = 1; |
14 | const B = 2; |
15 | const C = 4; |
16 | const D = 8; |
17 | } |
18 | } |
19 | |
20 | let flags = Flags::A | Flags::B; |
21 | |
22 | let serialized = serde_json::to_string(&flags).unwrap(); |
23 | |
24 | println!("{:?} -> {}" , flags, serialized); |
25 | |
26 | assert_eq!(serialized, r#""A | B""# ); |
27 | |
28 | let deserialized: Flags = serde_json::from_str(&serialized).unwrap(); |
29 | |
30 | println!("{} -> {:?}" , serialized, flags); |
31 | |
32 | assert_eq!(deserialized, flags); |
33 | } |
34 | |
35 | #[cfg (not(feature = "serde" ))] |
36 | fn main() {} |
37 | |