Add example

This commit is contained in:
Graham Esau 2019-09-15 16:29:57 +01:00
parent 4962e1f731
commit 8a507f38a1
2 changed files with 68 additions and 11 deletions

View file

@ -14,10 +14,17 @@ use serde::{Deserialize, Serialize};
struct MyStruct { struct MyStruct {
my_int: i32, my_int: i32,
my_nullable: Option<bool>, my_nullable: Option<bool>,
my_nested_struct: Nested,
}
#[derive(Deserialize, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
struct Nested {
#[serde(default)] #[serde(default)]
my_string: String, my_string: String,
#[serde(rename = "myArray")] #[serde(rename = "myArray")]
my_float_vec: Vec<f32>, my_float_vec: Vec<f32>,
my_recursive_struct: Option<Box<Nested>>,
} }
fn main() -> Result<(), Box<dyn std::error::Error>> { fn main() -> Result<(), Box<dyn std::error::Error>> {
@ -33,11 +40,13 @@ This outputs the following:
{ {
"$schema": "http://json-schema.org/draft-07/schema#", "$schema": "http://json-schema.org/draft-07/schema#",
"title": "MyStruct", "title": "MyStruct",
"type": "object",
"definitions": {
"Nested": {
"type": "object", "type": "object",
"required": [ "required": [
"myArray", "myArray",
"myInt", "myRecursiveStruct"
"myNullable"
], ],
"properties": { "properties": {
"myArray": { "myArray": {
@ -47,20 +56,42 @@ This outputs the following:
"format": "float" "format": "float"
} }
}, },
"myInt": { "myRecursiveStruct": {
"type": "integer", "anyOf": [
"format": "int32" {
"$ref": "#/definitions/Nested"
}, },
"myNullable": { {
"type": [ "type": "null"
"boolean", }
"null"
] ]
}, },
"myString": { "myString": {
"type": "string" "type": "string"
} }
} }
}
},
"required": [
"myInt",
"myNestedStruct",
"myNullable"
],
"properties": {
"myInt": {
"type": "integer",
"format": "int32"
},
"myNestedStruct": {
"$ref": "#/definitions/Nested"
},
"myNullable": {
"type": [
"boolean",
"null"
]
}
}
} }
``` ```

View file

@ -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<bool>,
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<f32>,
my_recursive_struct: Option<Box<Nested>>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let schema = schema_for!(MyStruct)?;
println!("{}", serde_json::to_string_pretty(&schema)?);
Ok(())
}