serde icon indicating copy to clipboard operation
serde copied to clipboard

Make serde behave differently for different formats

Open dariocurr opened this issue 1 year ago • 3 comments

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"}}

dariocurr avatar Sep 29 '23 15:09 dariocurr

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)]

dariocurr avatar Oct 02 '23 14:10 dariocurr

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.

JHenneberg avatar Oct 05 '23 10:10 JHenneberg

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.

mrwilby avatar Oct 11 '23 23:10 mrwilby