pub trait JsonSchemaAs<T: ?Sized> {
// Required methods
fn schema_name() -> String;
fn json_schema(gen: &mut SchemaGenerator) -> Schema;
// Provided methods
fn is_referenceable() -> bool { ... }
fn schema_id() -> Cow<'static, str> { ... }
}
schemars_0_8
only.Expand description
A type which can be described as a JSON schema document.
This trait is as SerializeAs
is to Serialize
but for JsonSchema
.
You can use it to make your custom SerializeAs
and DeserializeAs
types also support being described via JSON schemas.
It is used by the Schema
type in order to implement JsonSchema
for the relevant types. Schema
is used implicitly by the serde_as
macro to instruct schemars
on how to generate JSON schemas for fields
annotated with #[serde_as(as = "...")]
attributes.
§Examples
Suppose we have our very own PositiveInt
type. Then we could add support
for generating a schema from it like this
use serde_with::schemars_0_8::JsonSchemaAs;
use schemars::gen::SchemaGenerator;
use schemars::schema::Schema;
use schemars::JsonSchema;
struct PositiveInt;
impl SerializeAs<i32> for PositiveInt {
// ...
}
impl<'de> DeserializeAs<'de, i32> for PositiveInt {
// ...
}
impl JsonSchemaAs<i32> for PositiveInt {
fn schema_name() -> String {
"PositiveInt".into()
}
fn json_schema(gen: &mut SchemaGenerator) -> Schema {
let mut schema = <i32 as JsonSchema>::json_schema(gen).into_object();
schema.number().minimum = Some(0.0);
schema.into()
}
}
Required Methods§
sourcefn schema_name() -> String
fn schema_name() -> String
The name of the generated JSON Schema.
This is used as the title for root schemas, and the key within the root’s definitions
property for sub-schemas.
sourcefn json_schema(gen: &mut SchemaGenerator) -> Schema
fn json_schema(gen: &mut SchemaGenerator) -> Schema
Generates a JSON Schema for this type.
If the returned schema depends on any referenceable schemas, then this method will
add them to the SchemaGenerator
’s schema definitions.
This should not return a $ref
schema.
Provided Methods§
sourcefn is_referenceable() -> bool
fn is_referenceable() -> bool
Whether JSON Schemas generated for this type should be re-used where possible using the $ref
keyword.
For trivial types (such as primitives), this should return false
. For more complex types, it should return true
.
For recursive types, this must return true
to prevent infinite cycles when generating schemas.
By default, this returns true
.
sourcefn schema_id() -> Cow<'static, str>
fn schema_id() -> Cow<'static, str>
Returns a string that uniquely identifies the schema produced by this type.
This does not have to be a human-readable string, and the value will not itself be included in generated schemas.
If two types produce different schemas, then they must have different schema_id()
s,
but two types that produce identical schemas should ideally have the same schema_id()
.
The default implementation returns the same value as schema_name()
.