schemars icon indicating copy to clipboard operation
schemars copied to clipboard

Override Serde for schema generation only

Open NuSkooler opened this issue 1 year ago • 1 comments

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

NuSkooler avatar Dec 18 '23 04:12 NuSkooler

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.

GREsau avatar Aug 27 '24 19:08 GREsau