File: remote_derive.rs

package info (click to toggle)
rust-schemars 0.8.22-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,324 kB
  • sloc: makefile: 2
file content (43 lines) | stat: -rw-r--r-- 1,339 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
#![cfg(feature = "derive")]
// Pretend that this is somebody else's crate, not a module.
mod other_crate {
    // Neither Schemars nor the other crate provides a JsonSchema impl
    // for this struct.
    pub struct Duration {
        pub secs: i64,
        pub nanos: i32,
    }
}

////////////////////////////////////////////////////////////////////////////////

use other_crate::Duration;
use schemars::{schema_for, JsonSchema};

// This is just a copy of the remote data structure that Schemars can use to
// create a suitable JsonSchema impl.
#[derive(JsonSchema)]
#[serde(remote = "Duration")]
pub struct DurationDef {
    pub secs: i64,
    pub nanos: i32,
}

// Now the remote type can be used almost like it had its own JsonSchema impl
// all along. The `with` attribute gives the path to the definition for the
// remote type. Note that the real type of the field is the remote type, not
// the definition type.
#[derive(JsonSchema)]
pub struct Process {
    pub command_line: String,
    #[serde(with = "DurationDef")]
    pub wall_time: Duration,
    // Generic types must be explicitly specified with turbofix `::<>` syntax.
    #[serde(with = "Vec::<DurationDef>")]
    pub durations: Vec<Duration>,
}

fn main() {
    let schema = schema_for!(Process);
    println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}