GREsau / schemars

Generate JSON Schema documents from Rust code
https://graham.cool/schemars/
MIT License
803 stars 225 forks source link

skip_serializing_if = "Vec::is_empty" still marked as required #189

Open bmc-msft opened 1 year ago

bmc-msft commented 1 year ago

In the following example with skip_serializing_if, results in the field still being listed as required.

Example using skip_serializing_if

use schemars::{schema_for, JsonSchema};
use serde::{Deserialize, Serialize};

#[derive(Deserialize, Serialize, JsonSchema)]
pub struct MyStruct {
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub my_optional_vec: Vec<String>,
}

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

Resulting schema showing my_optional_vec incorrectly as required.

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "MyStruct",
  "type": "object",
  "required": [
    "my_optional_vec"
  ],
  "properties": {
    "my_optional_vec": {
      "type": "array",
      "items": {
        "type": "string"
      }
    }
  }
}
bmc-msft commented 1 year ago

Note, using the above example with an empty list vs a non-empty list render with Serde as below.

An example without data:

let empty = MyStruct {my_optional_vec: vec![]};
println!("{}", serde_json::to_string_pretty(&empty).unwrap());

results in the following:

{}

An example with data:

let not_empty = MyStruct {my_optional_vec: vec!["with data".to_string()]};
println!("{}", serde_json::to_string_pretty(&not_empty).unwrap());

results in:

{
  "my_optional_vec": [
    "with data"
  ]
}
richardvanbergen commented 1 year ago

From what I can tell, schemars doesn't support skip_serializing_if at all