Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.