Add Contract for generating separate serialize/deserialize schemas (#335)

This commit is contained in:
Graham Esau 2024-09-04 19:41:34 +01:00 committed by GitHub
parent 497333e91b
commit 05325d2b7c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
36 changed files with 1224 additions and 225 deletions

View file

@ -28,15 +28,14 @@ let my_schema = generator.into_root_schema_for::<MyStruct>();
See the API documentation for more info on how to use those types for custom schema generation.
### Serialize vs. Deserialize contract
Of particular note is the `contract` setting, which controls whether the generated schemas should describe how types are serialized or how they're *de*serialized. By default, this is set to `Deserialize`. If you instead want your schema to describe the serialization behaviour, modify the `contract` field of `SchemaSettings` or use the `for_serialize()` helper method:
{% include example.md name="serialize_contract" %}
## Schema from Example Value
If you want a schema for a type that can't/doesn't implement `JsonSchema`, but does implement `serde::Serialize`, then you can generate a JSON schema from a value of that type using the [`schema_for_value!` macro](https://docs.rs/schemars/1.0.0--latest/schemars/macro.schema_for_value.html). However, this schema will generally be less precise than if the type implemented `JsonSchema` - particularly when it involves enums, since schemars will not make any assumptions about the structure of an enum based on a single variant.
```rust
let value = MyStruct { foo = 123 };
let my_schema = schema_for_value!(value);
```
<!-- TODO:
create and link to example
-->
{% include example.md name="from_value" %}