So I have a JSON that looks like this :
{
"name": "customer",
"properties": [
{
"name": "id",
"type": "int",
"value": 32
},
{
"name": "name",
"type": "string",
"value": "John"
}
]
}
Currently I am deserializing to this set of struct :
#[derive(Serialize, Deserialize, Debug)]
struct Customer {
name: String,
properties: Vec<Property>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "name", content = "value")]
enum Property {
#[serde(rename = "id")]
Id(i32),
#[serde(rename = "name")]
Name(String),
}
But to avoid dealing with matching over enum every time I want to access a property I would like to deserialize it to a struct that looks like this :
struct Customer {
name: String,
properties: Properties,
}
struct Properties {
id: i32, // will be 32 as in the object containing the name "id".
name: String, // will be John as in the object containing the name "name".
}
Is this something that the serde
library allow in some way ? If so could you provide an example on how to achieve that ?
Note that I can't mess with the actual json structure so I am not interested in any solutions that requires that.
Thanks to edkeveked's answer I managed to find a solution that fits my needs pretty well.
Basically I rearranged the Deserializer to loop over the whole properties array and try to match every object in it with an Enum variant. I like this because I can easily map a new property in the future if it comes to it and it feels more flexible type-wise.
Anyway, here's the code for it :