schemars
schemars copied to clipboard
Support generating multiple schemas (for serialize vs deserialize) from the same struct
I have a lot of types whose deserialization behavior allows for more types than the serialization does. For example:
// Deserialize is implemented such that any non-string JSON object is stringified
#[derive(Serialize)]
struct LenientString(String);
#[derive(JsonSchema, Serialize, Deserialize)]
struct Foo {
bar: LenientString
}
Therefore I would like to generate two schemas per type: A schema describing the input that is allowed, and a schema that describes the output that is guaranteed.
Is this kind of feature something you'd be interested in merging? I am on the fence as to whether this is sensible. In some languages I would've created separate input and output types, but as serde allowed me to do everything with one type this is what I ended up with. But I think that adding this feature to schemars is easier than refactoring my existing codebase.
Interesting idea, this could indeed be useful. I would certainly consider altering the behaviour of json_schema()
to return the "deserialize" schema, and having a separate function to return the "serialize" schema (or vice versa). My main concern would be how much this increases the output binary size and/or compile times, but it may not be a big problem. If it is, it may be worth making it optional via a feature flag
This would also fix #25, since aliases are only significant when deserializing
Has there been any discussion on how this could be implemented?
As far as I can tell, generating examples is done via Serde serialize. This would mean, it's necessary to create at least one copy (as in generating a new struct at compiletime in a macro, not copying in the sense of struct.copy()
) of the struct that's deriving JsonSchema
to generate proper examples when #[serde(skip_serializing)]
is used. Otherwise those fields would be missing in a deserialize schema example.