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 {
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>> {
@ -33,11 +40,13 @@ This outputs the following:
{
"$schema": "http://json-schema.org/draft-07/schema#",
"title": "MyStruct",
"type": "object",
"definitions": {
"Nested": {
"type": "object",
"required": [
"myArray",
"myInt",
"myNullable"
"myRecursiveStruct"
],
"properties": {
"myArray": {
@ -47,20 +56,42 @@ This outputs the following:
"format": "float"
}
},
"myInt": {
"type": "integer",
"format": "int32"
"myRecursiveStruct": {
"anyOf": [
{
"$ref": "#/definitions/Nested"
},
"myNullable": {
"type": [
"boolean",
"null"
{
"type": "null"
}
]
},
"myString": {
"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(())
}