GREsau / schemars

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

Override Serde for schema generation only #260

Open NuSkooler opened 10 months ago

NuSkooler commented 10 months ago

We are using Schemars for schema generation in our project and it has been great!

I have a particular struct that is used to both deserialize from PascalCase XML and serialize to snake_case JSON. When creating a schema, the PascalCase is always used. Am I doing something wrong?

Example:

#[derive(JsonSchema, Serialize, Deserialize)]
#[serde(rename_all(deserialize = "PascalCase"))] // for XML input
#[serde(rename_all(serialize = "snake_case"))] // JSON output
pub struct MyStruct {
  pub foo Foo; // schema ends up with "Foo"
}

Edit: I also tried "overriding" Serde with a schemars declaration:

#[schemars(rename_all = "snake_case")]

But no luck

GREsau commented 2 months ago

Overriding it with the #[schemars(...)] attribute should work. I just tried this:

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

#[derive(JsonSchema, Serialize, Deserialize)]
#[serde(rename_all(deserialize = "PascalCase"))] // for XML input
#[serde(rename_all(serialize = "snake_case"))] // JSON output
#[schemars(rename_all = "snake_case")]
pub struct MyStruct {
    pub foo: i32,
}

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

And the generated schema always has the property foo, not Foo. This is the case both for schemars v0.8 and v1.0 alpha.