Skip to main content

json_schema_rs/
schema.rs

1use serde::Deserialize;
2use std::collections::BTreeMap;
3
4/// Wraps the JSON Schema `default` keyword to preserve `null`.
5/// Serde deserializes `Option<Value>` with JSON null as `None`; we need to
6/// distinguish absent key from `"default": null`.
7#[derive(Debug, Default)]
8pub enum DefaultKeyword {
9    /// Key "default" was absent from the schema.
10    #[default]
11    Absent,
12    /// Key "default" was present; the value may be `Value::Null`.
13    Present(serde_json::Value),
14}
15
16impl<'de> Deserialize<'de> for DefaultKeyword {
17    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
18    where
19        D: serde::Deserializer<'de>,
20    {
21        let v: serde_json::Value = Deserialize::deserialize(deserializer)?;
22        Ok(DefaultKeyword::Present(v))
23    }
24}
25
26/// Root or nested JSON Schema object.
27///
28/// Only the schema fields used by the generator are modeled.
29/// Extra keys in the JSON are ignored via serde's default behavior.
30/// Uses `BTreeMap` for deterministic property ordering (alphabetical by key).
31#[derive(Debug, Deserialize)]
32pub struct JsonSchema {
33    #[serde(default)]
34    pub title: Option<String>,
35
36    #[serde(default)]
37    pub description: Option<String>,
38
39    #[serde(default)]
40    pub r#type: Option<String>,
41
42    #[serde(default)]
43    pub properties: Option<BTreeMap<String, Box<JsonSchema>>>,
44
45    #[serde(default)]
46    pub required: Option<Vec<String>>,
47
48    /// Non-standard / draft-dependent keyword. We explicitly recognize it so it is
49    /// not treated as an unknown key, but we **ignore** it for codegen; required vs
50    /// optional is determined only by the object-level `required` array. Future
51    /// versions may add strict spec adherence or settings to allow/disallow or
52    /// interpret such fields.
53    #[serde(default)]
54    pub optional: Option<bool>,
55
56    #[serde(default)]
57    pub r#enum: Option<Vec<serde_json::Value>>,
58
59    #[serde(default)]
60    pub items: Option<Box<JsonSchema>>,
61
62    #[serde(default, rename = "additionalProperties")]
63    pub additional_properties: Option<serde_json::Value>,
64
65    #[serde(default)]
66    pub default: DefaultKeyword,
67
68    #[serde(default)]
69    pub minimum: Option<serde_json::Value>,
70
71    #[serde(default)]
72    pub maximum: Option<serde_json::Value>,
73}