3 ms·
Serde is very strong indeed (although not the easiest to understand, this would have been useful when I implemented a Serde library for [de]serialising with the
by kolektiv 7y ago
Serde is very strong indeed (although not the easiest to understand, this would have been useful when I implemented a Serde library for [de]serialising with the AWS DynamoDB AttributeValue format).
That said, I've always had a slight problem with this approach to serialisation in general, which is that it makes it very hard to have multiple serialisation approaches for a single type (e.g. I want one casing rule for one target, and a different one for another). This seems effectively impossible with an approach based on annotations/macros. Would love to know how others have dealt with that.
- JoshMcguigan 7y ago> I want one casing rule for one target, and a different one for another Hmm, this is interesting, and something I hadn't thought of before. I'd probably try to solve it with a combination of the newtype pattern (create wrapper types for `MyThing`, like `MyThingJson` and `MyThingToml`) and the Serde flatten attribute. Then you could, for example, add `#[serde(rename_all = "lowercase")]` to the `MyThingJson` struct and `#[serde(rename_all = "snake_case")]` to the `MyThingToml` struct. I haven't tested this though, so I'm not sure if the `rename_all` would flow through the flatten attribute as expected. Worst case you could duplicate the struct (or more likely, find or build a macro to do it for you) rather than use the newtype/flatten technique.
- dangets 7y agoThis is where I would either a) create 2 separate DTO representations with adapters to the internal domain object or b) have a trait which the 2 specialized structs implement. This conversion point is also a good place to do your validation that the object is in a consistent state. This isn't quite zero-cost - but it does isolate your external serialization code from your internal logic and it is easier to add even more formats in the future. And at least in Java-land is much cleaner than stacking lots and lots of annotations on the same struct.