GREsau / schemars

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

Schemars omit serde(flatten) BTreeMap #259

Closed JakkuSakura closed 2 months ago

JakkuSakura commented 10 months ago
use schemars::{schema_for, JsonSchema};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

#[derive(Serialize, Deserialize, JsonSchema)]
pub struct MyStruct {
    pub values: HashMap<String, String>,
    #[serde(flatten)]
    pub flatten: HashMap<String, String>,
}

fn main() {
    let schema = schema_for!(MyStruct);
    println!("{}", serde_json::to_string_pretty(&schema).unwrap());
}
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "MyStruct",
  "type": "object",
  "required": [
    "values"
  ],
  "properties": {
    "values": {
      "type": "object",
      "additionalProperties": {
        "type": "string"
      }
    }
  }
}
nightkr commented 7 months ago

That schema doesn't seem to correspond to those type definitions at all.

JakkuSakura commented 7 months ago

Sorry. I pasted the wrong rust type. I've updated the example

nightkr commented 7 months ago

Fwiw, it looks like a workaround for now is to add #[schemars(deny_unknown_fields)] to MyStruct.

GREsau commented 2 months ago

This is fixed in schemars 1.0.0-alpha.6 (and I think earlier alphas) - the output from the repro is now:

{
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "title": "MyStruct",
  "type": "object",
  "properties": {
    "values": {
      "type": "object",
      "additionalProperties": {
        "type": "string"
      }
    }
  },
  "additionalProperties": {
    "type": "string"
  },
  "required": [
    "values"
  ]
}