Skip to content

Error: missing field even when field is Optional<T> with serde_json #1154

@djkato

Description

@djkato

Hello, I share cynic types with surrealdb and need to be able to serialize from regular json.
in regular serde impl I think a missing field is serialized to None, but it seems cynic::QueryFragment doesn't like missing fields?

#[derive(cynic::QueryFragment, Debug, Clone, Serialize)]
pub struct Product {
    pub id: cynic::Id,
    #[cynic(flatten)]
    pub variants: Vec<ProductVariant>,
    pub name: String,
    //#[cynic(default)]: the trait bound `std::option::Option<Jsonstring>: IsScalar<JSONString>` is not satisfied
   //#[serde(default)]: doesn't do anything
    pub description: Option<Jsonstring>,
    pub category: Option<Category>,
    pub weight: Option<Weight>,
}

#[tokio::main]
async fn main() {
    // called `Result::unwrap()` on an `Err` value: Error("missing field `category`", line: 12, column: 3)
    let products: Vec<Product> = serde_json::from_str(&HUGE_JSON).unwrap();
    println!("{:?}", products);
}

const HUGE_JSON: &str = r##"
[
  {
    "id": "product:⟨UHJvZHVjdDoxMzE=⟩",
    "name": "Grey Hoodie",
    "variants": [],
    "weight": {
      "unit": "KG",
      "value": 0.0
    }
  }
]"##;

minimal reproduction:
https://github.com/djkato/cynic_serde_missing_field

Is there a way to make cynic turn missing fields into Option::None instead of throwing?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions