Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created July 31, 2019 20:59
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 rust-play/f89592cca7a67feab3b597dbe546f455 to your computer and use it in GitHub Desktop.
Save rust-play/f89592cca7a67feab3b597dbe546f455 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use serde::{Serialize, Deserialize}; // 1.0.97
use serde_json::{self, Value}; // 1.0.40
//use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
struct Stuff {
a: i32,
#[serde(flatten)]
extra: Maybe,
}
#[derive(Serialize, Deserialize, Debug)]
struct Extra {
__type: String,
#[serde(flatten)]
value: Value,
}
#[derive(Serialize, Deserialize, Debug)]
struct More {
b: i32,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(from = "Option<Extra>")]
enum Maybe {
More(More),
Unknown(String, Value),
Nothing,
}
impl From<Option<Extra>> for Maybe {
fn from(value: Option<Extra>) -> Maybe {
match value {
None => Maybe::Nothing,
Some(Extra { __type, value: value @ Value::Object(_) }) => {
match __type.as_str() {
"crate::Maybe" => Maybe::More(More::deserialize(value).unwrap()),
_ => Maybe::Unknown(__type, value),
}
},
Some(Extra { __type, value }) => {
Maybe::Unknown(__type, value)
},
}
}
}
// impl Serialize for Maybe {
// fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
// where
// S: Serializer,
// {
// match self {
// Maybe::More(more) => {
// let mut map = serializer.serialize_map(None)?;
// map.serialize_entry("__type", "crate::Maybe")?;
// map.end()
// }
// Maybe::Unknown(_hash_map) => unimplemented!(),
// }
// }
// }
fn main() {
//let x = Stuff { a: 1, extra: Some(Extra { b: Some(2), __type: "SomeType".into() }), extra2: Some(Extra { b: Some(2), __type: "SomeType".into() })};
//println!("{}", serde_json::to_string(&x).unwrap());
let x: Stuff = serde_json::from_str(r##"{"a":1,"__type":"crate::Maybe", "b": 2}"##).unwrap();
println!("{:?}", x);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment