Open kossnocorp opened 4 months ago
Here's another playground showing the issue, with comments explaining it.
Note that serde_json serializes JSON which it cannot deserialize. In my opinion, "to_string and from_str should always be compatible" is an important property of any derived Serialize/Deserialize
impl.
Update: I've found a StackOverflow anwer that helped me to come up with a solution. While it works, I think my proposal is still relevant. It will be great to automatically detect that structs are tagged or at least update the documentation. I'm willing to do either. Cheers!
If enums and structs all have tags assigned, serde_json ends up serializing it twice:
Here's the code:
Output:
Playground link
I expect that serde_json (or serde?) would recognize that structs have tags assigned and use them, allowing code like this:
However, it fails with:
I need to assign tags to structs, as it can be parsed or serialized as a standalone structure or part of an enum, so I must ensure
type
is always present. This is what I get when I don't add it:You can see that "Serialized post" and "Serialized comment" don't have
type
.Is there a way to work around it?
Would a contribution with a fix be welcome?
I didn't look at the code, so maybe it's impossible, but I think consuming struct's tags if there's no tag assigned to the enum would be a nice addition.
Alternatively, deduplicating
type
can be a solution, albeit not very correct.