-
-
Notifications
You must be signed in to change notification settings - Fork 779
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Support custom variant resolution mechanism #1212
Comments
You could either use the existing #[derive(Deserialize)]
#[serde(untagged, deny_unknown_fields)]
enum Untagged {
A {
a: String,
},
AB {
a: String,
b: String,
},
} or order the variants such that any variant with a superset of the fields of a different variant always appears earlier: #[derive(Deserialize)]
#[serde(untagged)]
enum Untagged {
AB {
a: String,
b: String,
},
A {
a: String,
},
} depending on whether you want unrecognized fields to error out or select the maximally matched variant (respectively). Beyond that, you could lose the |
The solution with I'm curious if it would valuable to have an option to *: https://play.rust-lang.org/?gist=61b91ff79ddd3ad4bb014c1378a28c5b&version=stable |
I would prefer to solve #773 without introducing another attribute. |
Ok, I'll close this. With improved error reporting I don't have anything that is unique to this issue. Thanks! |
I have a project where I need to pick the variant based on a strict set of the available fields.
Today I have the
untagged
container attribute to work with. While flexible, it's unable to disambiguate which variant to use in cases like these:I require deserialization to happen strictly based on the presence of a set of required fields which might overlap with required fields in other variants. This can be accomplished by looking at a strict set of available fields names at once, instead of only firing of a sequence of deserialization attempts.
Option 1: Support another container attribute
Support another container attribute which is specialized towards only matching a set of required fields.
This requires that each variant is also validated to not contain any optional fields. E.g. variant
A
would not be permitted to have an optional fieldb
.This approach could be considered overly specialized for a single use-case.
Solution 2: Provide the user with hooks to implement a custom variant resolution mechanism
One somewhat hacky option could be to permit the specification of a custom variant resolver through a custom function:
Because I'm not overly familiar with the internals of serde, I currently don't know how viable this approach would be.
The text was updated successfully, but these errors were encountered: