Add example for handling custom serialization
This commit is contained in:
parent
79155cddf5
commit
aec4824425
8 changed files with 170 additions and 2 deletions
48
docs/_includes/examples/custom_serialization.rs
Normal file
48
docs/_includes/examples/custom_serialization.rs
Normal file
|
@ -0,0 +1,48 @@
|
|||
use schemars::{schema_for, JsonSchema};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
// `int_as_string` and `bool_as_string` use the schema for `String`.
|
||||
#[derive(Default, Deserialize, Serialize, JsonSchema)]
|
||||
pub struct MyStruct {
|
||||
#[serde(default = "eight", with = "as_string")]
|
||||
#[schemars(with = "String")]
|
||||
pub int_as_string: i32,
|
||||
#[serde(default = "eight")]
|
||||
pub int_normal: i32,
|
||||
#[serde(default, with = "as_string")]
|
||||
#[schemars(with = "String")]
|
||||
pub bool_as_string: bool,
|
||||
#[serde(default)]
|
||||
pub bool_normal: bool,
|
||||
}
|
||||
|
||||
fn eight() -> i32 {
|
||||
8
|
||||
}
|
||||
|
||||
// This module serializes values as strings
|
||||
mod as_string {
|
||||
use serde::{de::Error, Deserialize, Deserializer, Serializer};
|
||||
|
||||
pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
|
||||
where
|
||||
T: std::fmt::Display,
|
||||
S: Serializer,
|
||||
{
|
||||
serializer.collect_str(value)
|
||||
}
|
||||
|
||||
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
|
||||
where
|
||||
T: std::str::FromStr,
|
||||
D: Deserializer<'de>,
|
||||
{
|
||||
let string = String::deserialize(deserializer)?;
|
||||
string.parse().map_err(|_| D::Error::custom("Input was not valid"))
|
||||
}
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let schema = schema_for!(MyStruct);
|
||||
println!("{}", serde_json::to_string_pretty(&schema).unwrap());
|
||||
}
|
24
docs/_includes/examples/custom_serialization.schema.json
Normal file
24
docs/_includes/examples/custom_serialization.schema.json
Normal file
|
@ -0,0 +1,24 @@
|
|||
{
|
||||
"$schema": "http://json-schema.org/draft-07/schema#",
|
||||
"title": "MyStruct",
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"bool_as_string": {
|
||||
"default": "false",
|
||||
"type": "string"
|
||||
},
|
||||
"bool_normal": {
|
||||
"default": false,
|
||||
"type": "boolean"
|
||||
},
|
||||
"int_as_string": {
|
||||
"default": "8",
|
||||
"type": "string"
|
||||
},
|
||||
"int_normal": {
|
||||
"default": 8,
|
||||
"type": "integer",
|
||||
"format": "int32"
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue