Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created June 12, 2019 08:13
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/96d2a1aa110a44769313b8b076666ce3 to your computer and use it in GitHub Desktop.
Save rust-play/96d2a1aa110a44769313b8b076666ce3 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
extern crate serde;
extern crate serde_derive;
extern crate serde_json;
use serde::{Deserialize, Deserializer};
use serde::de::Error;
use std::collections::HashMap;
#[derive(Debug, Deserialize, PartialEq)]
#[serde(tag = "type", content = "value")]
pub enum Value {
bool(bool),
float(f32),
int(u32),
color(u32),
string(String),
}
#[derive(Debug, Deserialize)]
struct Base {
#[serde(deserialize_with = "parse_prop")]
properties: HashMap<String, Value>,
x: u32, // decimal
}
pub fn parse_prop<'de, D>(
de: D,
) -> Result<HashMap<String, Value>, D::Error>
where
D: Deserializer<'de>,
{
let mut map = HashMap::new();
#[derive(Debug, Deserialize)]
struct Helper {
name: String,
#[serde(rename(deserialize = "type"))]
_type: String,
value: serde_json::Value, // want to map type + value input to value: Value
}
let s: Vec<Helper> = Deserialize::deserialize(de)?;
dbg!(&s);
Ok(map)
}
fn main() {
let raw = r##"
{
"properties":[
{
"name":"first_name",
"type":"int",
"value":1
},
{
"name": "test",
"type": "bool",
"value": false
}],
"x":0
}"##;
let test: Base = serde_json::from_str(raw).expect("Couldn't derserialize");
assert_eq!(test.x, 0);
dbg!(test);
//assert_eq!(test.properties["test"], Value::bool(false));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment