Using Serde Attributes
#[serde(...)]
attributes can be overriden (or replaced) with #[schemars(...)]
attributes, which behave identically. You may find this useful if you want to change the generated schema without affecting Serde's behaviour, or if you're just not using Serde.
use schemars::{schema_for, JsonSchema};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, JsonSchema)]
#[schemars(rename_all = "camelCase", deny_unknown_fields)]
pub struct MyStruct {
#[serde(rename = "thisIsOverridden")]
#[schemars(rename = "myNumber", range(min = 1, max = 10))]
pub my_int: i32,
pub my_bool: bool,
#[schemars(default)]
pub my_nullable_enum: Option<MyEnum>,
#[schemars(inner(regex(pattern = "^x$")))]
pub my_vec_str: Vec<String>,
}
#[derive(Deserialize, Serialize, JsonSchema)]
#[schemars(untagged)]
pub enum MyEnum {
StringNewType(#[schemars(phone)] String),
StructVariant {
#[schemars(length(min = 1, max = 100))]
floats: Vec<f32>,
},
}
fn main() {
let schema = schema_for!(MyStruct);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
Click to see the output JSON schema...
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MyStruct",
"type": "object",
"required": [
"myBool",
"myNumber",
"myVecStr"
],
"properties": {
"myBool": {
"type": "boolean"
},
"myNullableEnum": {
"default": null,
"anyOf": [
{
"$ref": "#/definitions/MyEnum"
},
{
"type": "null"
}
]
},
"myNumber": {
"type": "integer",
"format": "int32",
"maximum": 10.0,
"minimum": 1.0
},
"myVecStr": {
"type": "array",
"items": {
"type": "string",
"pattern": "^x$"
}
}
},
"additionalProperties": false,
"definitions": {
"MyEnum": {
"anyOf": [
{
"type": "string",
"format": "phone"
},
{
"type": "object",
"required": [
"floats"
],
"properties": {
"floats": {
"type": "array",
"items": {
"type": "number",
"format": "float"
},
"maxItems": 100,
"minItems": 1
}
}
}
]
}
}
}