Skip to content

Instantly share code, notes, and snippets.

@46bit
Last active February 19, 2017 15:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save 46bit/4f9a2daaa8a32cd27a5e7a39bf00154a to your computer and use it in GitHub Desktop.
Save 46bit/4f9a2daaa8a32cd27a5e7a39bf00154a to your computer and use it in GitHub Desktop.
extern crate serde;
#[macro_use]
extern crate serde_derive;
extern crate serde_json;
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
#[serde(tag = "tag")]
pub enum A {
A1 { field: B },
A2,
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum B {
B1,
B2,
}
fn main() {
// Construct an A containing a B.
let a = A::A1 { field: B::B1 };
println!("{:?}", a);
// Successfully serialises to `{"tag":"A1","field":"B1"}`.
let json = serde_json::to_string(&a).unwrap();
println!("{}", json);
// That correct, serde_json-generated JSON errors in the decode with
// `Syntax(Message("invalid type: string \"B1\", expected enum B"), 0, 0)`
let a_new: A = serde_json::from_str(json.as_str()).unwrap();
println!("{:?}", a_new);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment