File: custom_serialization.rs

package info (click to toggle)
rust-schemars 0.8.22-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,312 kB
  • sloc: makefile: 2
file content (61 lines) | stat: -rw-r--r-- 1,674 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#![cfg(feature = "derive")]
use schemars::schema::{Schema, SchemaObject};
use schemars::{r#gen::SchemaGenerator, 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(schema_with = "make_custom_schema")]
    pub bool_as_string: bool,

    #[serde(default)]
    pub bool_normal: bool,
}

fn make_custom_schema(generator: &mut SchemaGenerator) -> Schema {
    let mut schema: SchemaObject = <String>::json_schema(generator).into();
    schema.format = Some("boolean".to_owned());
    schema.into()
}

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());
}