| 1 | // Pretend that this is somebody else's crate, not a module. |
| 2 | mod other_crate { |
| 3 | // Neither Schemars nor the other crate provides a JsonSchema impl |
| 4 | // for this struct. |
| 5 | pub struct Duration { |
| 6 | pub secs: i64, |
| 7 | pub nanos: i32, |
| 8 | } |
| 9 | } |
| 10 | |
| 11 | //////////////////////////////////////////////////////////////////////////////// |
| 12 | |
| 13 | use other_crate::Duration; |
| 14 | use schemars::{schema_for, JsonSchema}; |
| 15 | |
| 16 | // This is just a copy of the remote data structure that Schemars can use to |
| 17 | // create a suitable JsonSchema impl. |
| 18 | #[derive(JsonSchema)] |
| 19 | #[serde(remote = "Duration")] |
| 20 | pub struct DurationDef { |
| 21 | pub secs: i64, |
| 22 | pub nanos: i32, |
| 23 | } |
| 24 | |
| 25 | // Now the remote type can be used almost like it had its own JsonSchema impl |
| 26 | // all along. The `with` attribute gives the path to the definition for the |
| 27 | // remote type. Note that the real type of the field is the remote type, not |
| 28 | // the definition type. |
| 29 | #[derive(JsonSchema)] |
| 30 | pub struct Process { |
| 31 | pub command_line: String, |
| 32 | #[serde(with = "DurationDef")] |
| 33 | pub wall_time: Duration, |
| 34 | // Generic types must be explicitly specified with turbofix `::<>` syntax. |
| 35 | #[serde(with = "Vec::<DurationDef>")] |
| 36 | pub durations: Vec<Duration>, |
| 37 | } |
| 38 | |
| 39 | fn main() { |
| 40 | let schema = schema_for!(Process); |
| 41 | println!("{}", serde_json::to_string_pretty(&schema).unwrap()); |
| 42 | } |