### Implement Visitor in schemars 0.8 Source: https://graham.cool/schemars/migrating Example of a custom Visitor implementation used in older versions of schemars. ```rust use schemars::schema::SchemaObject; use schemars::visit::{visit_schema_object, Visitor}; pub struct MyVisitor; impl Visitor for MyVisitor { fn visit_schema_object(&mut self, schema: &mut SchemaObject) { // First, make our change to this schema schema .extensions .insert("my_property".to_string(), serde_json::json!("hello world")); // Then delegate to default implementation to visit any subschemas visit_schema_object(self, schema); } } let mut schema = schemars::schema_for!(str); MyVisitor.visit_root_schema(&mut schema); ``` -------------------------------- ### Generate Schema from Value Example Source: https://graham.cool/schemars/examples/9-from_value Demonstrates using the schema_for_value! macro with a struct containing an enum. ```rust use schemars::schema_for_value; use serde::Serialize; #[derive(Serialize)] pub struct MyStruct { pub my_int: i32, pub my_bool: bool, pub my_nullable_enum: Option, } #[derive(Serialize)] pub enum MyEnum { StringNewType(String), StructVariant { floats: Vec }, } fn main() { let schema = schema_for_value!(MyStruct { my_int: 123, my_bool: true, my_nullable_enum: Some(MyEnum::StringNewType("foo".to_string())) }); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Serialized schema output Source: https://graham.cool/schemars/generating The resulting JSON schema output from the serialization contract example. ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "MyStruct", "type": "object", "properties": { "definitely_string": { "type": "string" }, "maybe_string": { "type": "string" }, "my_int": { "type": "integer", "format": "int32" }, "my_read_only_bool": { "type": "boolean", "default": false, "readOnly": true } }, "required": [ "my_int", "my_read_only_bool", "definitely_string" ] } ``` -------------------------------- ### Generated JSON Schema Output Source: https://graham.cool/schemars/examples/5-remote_derive The resulting JSON schema structure produced by the remote derivation example. ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "Process", "type": "object", "properties": { "command_line": { "type": "string" }, "durations": { "type": "array", "items": { "$ref": "#/$defs/Duration" } }, "wall_time": { "$ref": "#/$defs/Duration" } }, "required": [ "command_line", "wall_time", "durations" ], "$defs": { "Duration": { "type": "object", "properties": { "nanos": { "type": "integer", "format": "int32" }, "secs": { "type": "integer", "format": "int64" } }, "required": [ "secs", "nanos" ] } } } ``` -------------------------------- ### Generated JSON schema output Source: https://graham.cool/schemars/examples/2-serde_attrs The resulting JSON schema produced by the provided Rust code example. ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "MyStruct", "type": "object", "properties": { "myBool": { "type": "boolean" }, "myNullableEnum": { "anyOf": [ { "$ref": "#/$defs/MyEnum" }, { "type": "null" } ], "default": null }, "myNumber": { "type": "integer", "format": "int32" } }, "additionalProperties": false, "required": [ "myNumber", "myBool" ], "$defs": { "MyEnum": { "anyOf": [ { "type": "string" }, { "type": "object", "properties": { "floats": { "type": "array", "items": { "type": "number", "format": "float" } } }, "required": [ "floats" ] } ] } } } ``` -------------------------------- ### Generated JSON Schema Output Source: https://graham.cool/schemars/examples/3-schemars_attrs The resulting JSON schema produced by the provided Rust code example. ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "MyStruct", "type": "object", "properties": { "myBool": { "type": "boolean" }, "myNullableEnum": { "anyOf": [ { "$ref": "#/$defs/MyEnum" }, { "type": "null" } ], "default": null }, "myNumber": { "type": "integer", "maximum": 10, "minimum": 1 }, "myVecStr": { "type": "array", "items": { "type": "string", "pattern": "^x$" } } }, "additionalProperties": false, "required": [ "myNumber", "myBool", "myVecStr" ], "x-customProperty": "example", "$defs": { "MyEnum": { "anyOf": [ { "type": "string", "format": "email" }, { "type": "object", "properties": { "floats": { "type": "array", "items": { "type": "number", "format": "float" }, "maxItems": 100, "minItems": 1 } }, "required": [ "floats" ] } ] } } } ``` -------------------------------- ### Implement JsonSchema for a non-generic type Source: https://graham.cool/schemars/implementing A complete example of implementing the JsonSchema trait for a type without generic parameters. ```rust impl JsonSchema for NonGenericType { fn schema_name() -> Cow<'static, str> { // Exclude the module path to make the name in generated schemas clearer. "NonGenericType".into() } fn schema_id() -> Cow<'static, str> { // Include the module, in case a type with the same name is in another module/crate concat!(module_path!(), "::NonGenericType").into() } fn json_schema(_gen: &mut SchemaGenerator) -> Schema { json_schema!({ "type": "object", "foo": "bar" }) } } ``` -------------------------------- ### Create and modify Schema in v1.0 Source: https://graham.cool/schemars/migrating Demonstrates the updated approach using the json_schema! macro and direct manipulation of the underlying serde_json::Value. ```rust use schemars::{json_schema, Schema}; // Create a Schema for an object with property `foo` let mut schema: Schema = json_schema!({ "type": "object", "properties": { "foo": true } }); // Make the `foo` property required schema .ensure_object() .entry("required") .or_insert(serde_json::Value::Array(Vec::new())) .as_array_mut() .expect("`required` should be an array") .push("foo".into()); ``` -------------------------------- ### Configure Schema Generation Settings Source: https://graham.cool/schemars/examples/4-custom_settings Demonstrates using SchemaSettings to customize the generator, such as disabling the meta-schema and enabling subschema inlining. ```rust use schemars::{generate::SchemaSettings, JsonSchema}; #[derive(JsonSchema)] pub struct MyStruct { pub my_int: i32, pub my_bool: bool, pub my_nullable_enum: Option, } #[derive(JsonSchema)] pub enum MyEnum { StringNewType(String), StructVariant { floats: Vec }, } fn main() { let settings = SchemaSettings::draft07().with(|s| { s.meta_schema = None; s.inline_subschemas = true; }); let generator = settings.into_generator(); let schema = generator.into_root_schema_for::(); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Define Structs and Enums with Doc Comments Source: https://graham.cool/schemars/examples/6-doc_comments Use triple-slash doc comments to define titles and descriptions for generated JSON schemas. ```rust use schemars::{schema_for, JsonSchema}; /// # My Amazing Struct /// This struct shows off generating a schema with /// a custom title and description. #[derive(JsonSchema)] pub struct MyStruct { /// # My Amazing Integer pub my_int: i32, /// This bool has a description, but no title. pub my_bool: bool, /// # A Nullable Enum /// This enum might be set, or it might not. pub my_nullable_enum: Option, } /// # My Amazing Enum #[derive(JsonSchema)] pub enum MyEnum { /// A wrapper around a `String` StringNewType(String), /// A struct-like enum variant which contains /// some floats StructVariant { /// The floats themselves floats: Vec, }, } fn main() { let schema = schema_for!(MyStruct); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Create and modify Schema in v0.8 Source: https://graham.cool/schemars/migrating Demonstrates the legacy approach of using SchemaObject and explicit struct fields to define and modify schema properties. ```rust use schemars::schema::{InstanceType, ObjectValidation, Schema, SchemaObject}; use schemars::Map; // Create a Schema for an object with property `foo` let schema_object = SchemaObject { instance_type: Some(InstanceType::Object.into()), object: Some(Box::new(ObjectValidation { properties: Map::from_iter([("foo".to_owned(), true.into())]), ..Default::default() })), ..Default::default() }; let schema: Schema = schema_object.into(); // Make the `foo` property required let mut schema_object = schema.into_object(); let obj = schema_object.object(); obj.required.insert("foo".to_owned()); ``` -------------------------------- ### Generate a basic schema Source: https://graham.cool/schemars/generating Use the schema_for! macro to generate a schema for a type that implements JsonSchema. ```rust let my_schema = schema_for!(MyStruct); ``` -------------------------------- ### Apply Serde attributes to Rust structs and enums Source: https://graham.cool/schemars/examples/2-serde_attrs Demonstrates using attributes like rename_all, deny_unknown_fields, rename, and default to influence schema generation. ```rust use schemars::{schema_for, JsonSchema}; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, JsonSchema)] #[serde(rename_all = "camelCase", deny_unknown_fields)] pub struct MyStruct { #[serde(rename = "myNumber")] pub my_int: i32, pub my_bool: bool, #[serde(default)] pub my_nullable_enum: Option, } #[derive(Deserialize, Serialize, JsonSchema)] #[serde(untagged)] pub enum MyEnum { StringNewType(String), StructVariant { floats: Vec }, } fn main() { let schema = schema_for!(MyStruct); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Configure serialization contract Source: https://graham.cool/schemars/generating Modify SchemaSettings to generate schemas describing serialization behavior instead of the default deserialization behavior. ```rust use schemars::{generate::SchemaSettings, JsonSchema}; use serde::{Deserialize, Serialize}; #[derive(JsonSchema, Deserialize, Serialize)] // The schema effectively ignores this `rename_all`, since it doesn't apply to serialization #[serde(rename_all(deserialize = "PascalCase"))] pub struct MyStruct { pub my_int: i32, #[serde(skip_deserializing)] pub my_read_only_bool: bool, // This property is excluded from the schema #[serde(skip_serializing)] pub my_write_only_bool: bool, // This property is excluded from the "required" properties of the schema, because it may be // be skipped during serialization #[serde(skip_serializing_if = "str::is_empty")] pub maybe_string: String, pub definitely_string: String, } fn main() { // By default, generated schemas describe how types are deserialized. // So we modify the settings here to instead generate schemas describing how it's serialized: let settings = SchemaSettings::default().for_serialize(); let generator = settings.into_generator(); let schema = generator.into_root_schema_for::(); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Generate a Draft 7 schema Source: https://graham.cool/schemars/generating Configure the schema generator to conform to a specific JSON Schema draft version. ```rust let generator = SchemaSettings::draft07().into_generator(); let my_schema = generator.into_root_schema_for::(); ``` -------------------------------- ### Customizing Schema Generation with Schemars Attributes Source: https://graham.cool/schemars/examples/3-schemars_attrs Demonstrates applying various schemars attributes to structs and enums to influence the generated JSON schema. ```rust use schemars::{schema_for, JsonSchema, Schema}; use serde::{Deserialize, Serialize}; #[derive(Deserialize, Serialize, JsonSchema)] #[schemars(rename_all = "camelCase", deny_unknown_fields, extend("x-customProperty" = "example"))] pub struct MyStruct { #[serde(rename = "thisIsOverridden")] #[schemars(rename = "myNumber", range(min = 1, max = 10), transform = remove_format)] pub my_int: i32, pub my_bool: bool, #[schemars(default)] pub my_nullable_enum: Option, #[schemars(inner(regex(pattern = "^x$")))] pub my_vec_str: Vec, } #[derive(Deserialize, Serialize, JsonSchema)] #[schemars(untagged)] pub enum MyEnum { StringNewType(#[schemars(email)] String), StructVariant { #[schemars(length(min = 1, max = 100))] floats: Vec, }, } fn remove_format(schema: &mut Schema) { schema.remove("format"); } fn main() { let schema = schema_for!(MyStruct); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Define schema_name function Source: https://graham.cool/schemars/implementing Returns the human-readable name of the type's schema. ```rust fn schema_name() -> Cow<'static, str>; ``` -------------------------------- ### Deriving JsonSchema with custom serialization attributes Source: https://graham.cool/schemars/examples/7-custom_serialization Demonstrates overriding schema generation for fields using custom serialization modules. ```rust use schemars::{schema_for, JsonSchema, Schema, SchemaGenerator}; use serde::{Deserialize, Serialize}; // `int_as_string` and `bool_as_string` use the schema for `String`. #[derive(Default, Deserialize, Serialize, JsonSchema)] pub struct MyStruct { #[serde(default = "eight", with = "as_string")] #[schemars(with = "String")] pub int_as_string: i32, #[serde(default = "eight")] pub int_normal: i32, #[serde(default, with = "as_string")] #[schemars(schema_with = "make_custom_schema")] pub bool_as_string: bool, #[serde(default)] pub bool_normal: bool, } fn make_custom_schema(generator: &mut SchemaGenerator) -> Schema { let mut schema = String::json_schema(generator); schema.insert("format".into(), "boolean".into()); schema } fn eight() -> i32 { 8 } // This module serializes values as strings mod as_string { use serde::{de::Error, Deserialize, Deserializer, Serializer}; pub fn serialize(value: &T, serializer: S) -> Result where T: std::fmt::Display, S: Serializer, { serializer.collect_str(value) } pub fn deserialize<'de, T, D>(deserializer: D) -> Result where T: std::str::FromStr, D: Deserializer<'de>, { let string = String::deserialize(deserializer)?; string .parse() .map_err(|_| D::Error::custom("Input was not valid")) } } fn main() { let schema = schema_for!(MyStruct); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Enable Chrono support in Cargo.toml Source: https://graham.cool/schemars/features Add the chrono04 feature to the schemars dependency to enable JsonSchema implementation for chrono types. ```toml [dependencies] schemars = { version = "0.9.0", features = ["chrono04"] } ``` -------------------------------- ### Remote Deriving JsonSchema for External Types Source: https://graham.cool/schemars/examples/5-remote_derive Define a local struct mirroring the external type and use the #[serde(remote = ...)] attribute. Apply the #[serde(with = ...)] attribute on fields using the remote type to reference the proxy definition. ```rust // Pretend that this is somebody else's crate, not a module. mod other_crate { // Neither Schemars nor the other crate provides a JsonSchema impl // for this struct. pub struct Duration { pub secs: i64, pub nanos: i32, } } //////////////////////////////////////////////////////////////////////////////// use other_crate::Duration; use schemars::{schema_for, JsonSchema}; // This is just a copy of the remote data structure that Schemars can use to // create a suitable JsonSchema impl. #[derive(JsonSchema)] #[serde(remote = "Duration")] pub struct DurationDef { pub secs: i64, pub nanos: i32, } // Now the remote type can be used almost like it had its own JsonSchema impl // all along. The `with` attribute gives the path to the definition for the // remote type. Note that the real type of the field is the remote type, not // the definition type. #[derive(JsonSchema)] pub struct Process { pub command_line: String, #[serde(with = "DurationDef")] pub wall_time: Duration, // Generic types must be explicitly specified with turbofix `::<>` syntax. #[serde(with = "Vec::")] pub durations: Vec, } fn main() { let schema = schema_for!(Process); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` -------------------------------- ### Generated JSON Schema Output Source: https://graham.cool/schemars/examples/9-from_value The resulting JSON schema generated from the provided MyStruct instance. ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "MyStruct", "type": "object", "properties": { "my_bool": { "type": "boolean" }, "my_int": { "type": "integer" }, "my_nullable_enum": true }, "examples": [ { "my_bool": true, "my_int": 123, "my_nullable_enum": { "StringNewType": "foo" } } ] } ``` -------------------------------- ### Generated JSON Schema Output Source: https://graham.cool/schemars/examples/8-enum_repr The resulting JSON schema for the SmallPrime enum, showing the integer type and enum values. ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "SmallPrime", "type": "integer", "enum": [ 2, 3, 5, 7 ] } ``` -------------------------------- ### Implement Transform in schemars 1.0 Source: https://graham.cool/schemars/migrating Equivalent implementation using the new Transform trait. ```rust use schemars::transform::{transform_subschemas, Transform}; use schemars::Schema; pub struct MyTransform; impl Transform for MyTransform { fn transform(&mut self, schema: &mut Schema) { // First, make our change to this schema schema.insert("my_property".to_string(), serde_json::json!("hello world")); // Then apply the transform to any subschemas transform_subschemas(self, schema); } } let mut schema = schemars::schema_for!(str); MyTransform.transform(&mut schema); ``` -------------------------------- ### Define json_schema function Source: https://graham.cool/schemars/implementing Creates the actual JSON schema for the type, using the provided generator to handle subschemas. ```rust fn json_schema(generator: &mut SchemaGenerator) -> Schema; ``` -------------------------------- ### Extend Schema Properties Source: https://graham.cool/schemars/deriving/attributes Use the extend attribute to add or replace properties in a generated schema using key-value pairs. ```rust #[derive(JsonSchema)] #[schemars(extend("simple" = "string value", "complex" = {"array": [1, 2, 3]}))] struct Struct; ``` -------------------------------- ### Define Transform as a function Source: https://graham.cool/schemars/migrating Transform can be implemented as a function that accepts a &mut Schema argument. ```rust fn my_transform(schema: &mut Schema) { // First, make our change to this schema schema.insert("my_property".to_string(), serde_json::json!("hello world")); // Then apply the transform to any subschemas transform_subschemas(&mut my_transform, schema); } let mut schema = schemars::schema_for!(str); my_transform(&mut schema); // Or equivalently: // my_transform.transform(&mut schema); ``` -------------------------------- ### Generated JSON Schema Output Source: https://graham.cool/schemars/examples/4-custom_settings The resulting JSON schema structure produced by the custom generator settings. ```json { "title": "MyStruct", "type": "object", "properties": { "my_bool": { "type": "boolean" }, "my_int": { "type": "integer", "format": "int32" }, "my_nullable_enum": { "anyOf": [ { "oneOf": [ { "type": "object", "properties": { "StringNewType": { "type": "string" } }, "additionalProperties": false, "required": [ "StringNewType" ] }, { "type": "object", "properties": { "StructVariant": { "type": "object", "properties": { "floats": { "type": "array", "items": { "type": "number", "format": "float" } } }, "required": [ "floats" ] } }, "additionalProperties": false, "required": [ "StructVariant" ] } ] }, { "type": "null" } ] } }, "required": [ "my_int", "my_bool" ] } ``` -------------------------------- ### Generated JSON Schema output Source: https://graham.cool/schemars/examples/7-custom_serialization The resulting JSON schema output for the MyStruct definition. ```json { "$schema": "https://json-schema.org/draft/2020-12/schema", "title": "MyStruct", "type": "object", "properties": { "bool_as_string": { "type": "string", "format": "boolean", "default": "false" }, "bool_normal": { "type": "boolean", "default": false }, "int_as_string": { "type": "string", "default": "8" }, "int_normal": { "type": "integer", "format": "int32", "default": 8 } } } ``` -------------------------------- ### Derive JsonSchema for a struct Source: https://graham.cool/schemars/deriving Use the #[derive(JsonSchema)] attribute to automatically generate a JSON schema for a struct. The schema_for! macro is then used to generate the schema object at runtime. ```rust use schemars::{JsonSchema, schema_for}; #[derive(JsonSchema, Debug)] struct Point { x: i32, y: i32, } fn main() { let schema = schema_for!(Point); let serialized = serde_json::to_string(&schema).unwrap(); println!("{}", serialized); } ``` -------------------------------- ### Define inline_schema function Source: https://graham.cool/schemars/implementing Determines whether the schema should be inlined or referenced via $ref. Must return false for recursive types to avoid infinite cycles. ```rust fn inline_schema() -> bool; ``` -------------------------------- ### Apply Schema Transformations Source: https://graham.cool/schemars/deriving/attributes Use the transform attribute to apply custom logic to a generated schema via a function implementing the Transform trait. ```rust fn my_transform(schema: &mut Schema) { todo!() } #[derive(JsonSchema)] #[schemars(transform = my_transform)] struct Struct; ``` -------------------------------- ### Apply inner validation to array items Source: https://graham.cool/schemars/deriving/attributes Demonstrates using the inner attribute to apply validation constraints to elements within a collection. ```rust struct Struct { #[schemars(inner(url, pattern("^https://")))] urls: Vec, } ``` -------------------------------- ### Unsetting Serde attributes with schemars Source: https://graham.cool/schemars/deriving/attributes Use the ! prefix in a schemars attribute to ignore a corresponding serde attribute. ```rust #[derive(Deserialize, Serialize, JsonSchema)] #[serde(from = "OtherType")] // this makes schemars ignore the `from = "OtherType"` from the serde attribute: #[schemars(!from)] pub struct MyStruct { // ... } ``` -------------------------------- ### Use RecursiveTransform for non-recursive transforms Source: https://graham.cool/schemars/migrating Convert a non-recursive Transform into a recursive one using the RecursiveTransform newtype. ```rust fn my_transform2(schema: &mut Schema) { schema.insert("my_property".to_string(), serde_json::json!("hello world")); } let mut schema = schemars::schema_for!(str); RecursiveTransform(my_transform2).transform(&mut schema); ``` -------------------------------- ### Define schema_id function Source: https://graham.cool/schemars/implementing Returns a unique identifier for the type's schema to ensure Schemars treats identical types correctly. ```rust fn schema_id() -> Cow<'static, str>; ``` ```rust fn schema_id() -> Cow<'static, str> { format!("[{}]", T::schema_id()).into() } ``` -------------------------------- ### Derive JsonSchema_repr for Enums Source: https://graham.cool/schemars/examples/8-enum_repr Use JsonSchema_repr to generate a schema where the enum is represented as an integer type. ```rust use schemars::{schema_for, JsonSchema_repr}; #[derive(JsonSchema_repr)] #[repr(u8)] enum SmallPrime { Two = 2, Three = 3, Five = 5, Seven = 7, } fn main() { let schema = schema_for!(SmallPrime); println!("{}", serde_json::to_string_pretty(&schema).unwrap()); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.