serde
serde copied to clipboard
Make serde behave differently for different formats
Hi. First of all thanks for this awesome crate.
I was wondering if there is a way to make serde
behave differently for different extensions.
In my use case. I need to serialize and deserialize in both JSON and YAML, so I am using serde_json
and serde_yaml
, but I want to set different attributes depending on whether I am serializing in JSON or YAML. Is this feasible?
More in detail. I need to ignore every attribute when I am serializing to JSON.
To give an example. Let's assume we have the following struct:
struct Family:
members: HashMap<String, String>
and that the members are:
- father: John
- mother: Mary
Then in YAML I'd like to have:
father: John
mother: Mary
while in JSON:
{"members": {"father": "John", "mother": "Mary"}}
From a DevEx point of view, I guess a fancy possible solution could allow the user to specify the serde attributes in the serde extensions identifiers. Then, if I want the attribute to apply to all extension I'd write
#[serde(flatten)]
while, if I want to apply the attribute just for YAML I'd write:
#[serde_yaml(flatten)]
I had the same problem. Data was differently structured in *.json compared to *.csv (#[serde(flatten)]
). I ended up creating to stucts to work around.
I have the same issue. Came here looking for the solution, but will probably go with the two structs route. Would be nice if there was a way to do this.