From 8a507f38a1da836346b60c6e738150b8ba75963e Mon Sep 17 00:00:00 2001 From: Graham Esau Date: Sun, 15 Sep 2019 16:29:57 +0100 Subject: [PATCH] Add example --- README.md | 53 ++++++++++++++++++++++++++++-------- schemars/examples/structs.rs | 26 ++++++++++++++++++ 2 files changed, 68 insertions(+), 11 deletions(-) create mode 100644 schemars/examples/structs.rs diff --git a/README.md b/README.md index a18b37a..3bc415b 100644 --- a/README.md +++ b/README.md @@ -14,10 +14,17 @@ use serde::{Deserialize, Serialize}; struct MyStruct { my_int: i32, my_nullable: Option, + my_nested_struct: Nested, +} + +#[derive(Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +struct Nested { #[serde(default)] my_string: String, #[serde(rename = "myArray")] my_float_vec: Vec, + my_recursive_struct: Option>, } fn main() -> Result<(), Box> { @@ -34,31 +41,55 @@ This outputs the following: "$schema": "http://json-schema.org/draft-07/schema#", "title": "MyStruct", "type": "object", + "definitions": { + "Nested": { + "type": "object", + "required": [ + "myArray", + "myRecursiveStruct" + ], + "properties": { + "myArray": { + "type": "array", + "items": { + "type": "number", + "format": "float" + } + }, + "myRecursiveStruct": { + "anyOf": [ + { + "$ref": "#/definitions/Nested" + }, + { + "type": "null" + } + ] + }, + "myString": { + "type": "string" + } + } + } + }, "required": [ - "myArray", "myInt", + "myNestedStruct", "myNullable" ], "properties": { - "myArray": { - "type": "array", - "items": { - "type": "number", - "format": "float" - } - }, "myInt": { "type": "integer", "format": "int32" }, + "myNestedStruct": { + "$ref": "#/definitions/Nested" + }, "myNullable": { "type": [ "boolean", "null" ] - }, - "myString": { - "type": "string" } } } diff --git a/schemars/examples/structs.rs b/schemars/examples/structs.rs new file mode 100644 index 0000000..2c53101 --- /dev/null +++ b/schemars/examples/structs.rs @@ -0,0 +1,26 @@ +use schemars::{JsonSchema, schema_for}; +use serde::{Deserialize, Serialize}; + +#[derive(Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +struct MyStruct { + my_int: i32, + my_nullable: Option, + my_nested_struct: Nested, +} + +#[derive(Deserialize, Serialize, JsonSchema)] +#[serde(rename_all = "camelCase")] +struct Nested { + #[serde(default)] + my_string: String, + #[serde(rename = "myArray")] + my_float_vec: Vec, + my_recursive_struct: Option>, +} + +fn main() -> Result<(), Box> { + let schema = schema_for!(MyStruct)?; + println!("{}", serde_json::to_string_pretty(&schema)?); + Ok(()) +}