schemars
schemars copied to clipboard
skip_serializing_if = "Vec::is_empty" still marked as required
trafficstars
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"
}
}
}
}
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(¬_empty).unwrap());
results in:
{
"my_optional_vec": [
"with data"
]
}
From what I can tell, schemars doesn't support skip_serializing_if at all