Add example for schemars attributes

This commit is contained in:
Graham Esau 2019-12-26 22:20:53 +00:00
parent 601fc3aaad
commit b11536e527
7 changed files with 175 additions and 2 deletions

View file

@ -0,0 +1,27 @@
use schemars::{schema_for, JsonSchema};
use serde::{Deserialize, Serialize};
#[derive(Deserialize, Serialize, JsonSchema)]
#[schemars(rename_all = "camelCase")]
pub struct MyStruct {
#[serde(rename = "thisIsOverridden")]
#[schemars(rename = "myNumber")]
pub my_int: i32,
pub my_bool: bool,
#[schemars(default)]
pub my_nullable_enum: Option<MyEnum>,
}
#[derive(Deserialize, Serialize, JsonSchema)]
#[schemars(untagged)]
pub enum MyEnum {
StringNewType(String),
StructVariant {
floats: Vec<f32>,
}
}
fn main() {
let schema = schema_for!(MyStruct);
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}

View file

@ -0,0 +1,53 @@
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MyStruct",
"type": "object",
"required": [
"myBool",
"myNumber"
],
"properties": {
"myBool": {
"type": "boolean"
},
"myNullableEnum": {
"default": null,
"anyOf": [
{
"$ref": "#/definitions/MyEnum"
},
{
"type": "null"
}
]
},
"myNumber": {
"type": "integer",
"format": "int32"
}
},
"definitions": {
"MyEnum": {
"anyOf": [
{
"type": "string"
},
{
"type": "object",
"required": [
"floats"
],
"properties": {
"floats": {
"type": "array",
"items": {
"type": "number",
"format": "float"
}
}
}
}
]
}
}
}