schemars icon indicating copy to clipboard operation
schemars copied to clipboard

Schemars omit serde(flatten) BTreeMap

Open JakkuSakura opened this issue 1 year ago • 3 comments

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"
      }
    }
  }
}

JakkuSakura avatar Dec 16 '23 04:12 JakkuSakura

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

nightkr avatar Mar 22 '24 16:03 nightkr

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

JakkuSakura avatar Mar 22 '24 16:03 JakkuSakura

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

nightkr avatar Mar 22 '24 16:03 nightkr

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"
  ]
}

GREsau avatar Aug 18 '24 19:08 GREsau