Skip to content

deserialize_default_from_empty_object works differently when default tag is set on inner struct #6

@georgemp

Description

@georgemp

Hi,

With the example here, if we tag InnerStruct with #[serde(default)], then the test with empty object fails. A default InnerStruct is created on the struct MyStruct, instead of None. I believe the default for an Option is None. So, not sure why a default object is being constructed in place of it. I have added comments to the relevant sections of the code.

extern crate serde_json;
extern crate serde_aux;
extern crate serde;

use serde_aux::prelude::*;

#[derive(Serialize, Deserialize, Debug)]
struct MyStruct {
    #[serde(deserialize_with = "deserialize_default_from_empty_object")]
    empty_as_default: Option<MyInnerStruct>,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(default)] //Added this, so that mandatory will be set to 0, if the field is missing from json.
struct MyInnerStruct {
    mandatory: u64,
}

fn main() {
    let s = r#" { "empty_as_default": { "mandatory": 42 } } "#;
    let a: MyStruct = serde_json::from_str(s).unwrap();
    assert_eq!(a.empty_as_default.unwrap().mandatory, 42);

    let s = r#" { "empty_as_default": null } "#;
    let a: MyStruct = serde_json::from_str(s).unwrap();
    assert!(a.empty_as_default.is_none());

    let s = r#" { "empty_as_default": {} } "#;
    let a: MyStruct = serde_json::from_str(s).unwrap(); 
    assert!(a.empty_as_default.is_none()); //This assert fails

    let s = r#" { "empty_as_default": { "unknown": 42 } } "#;
    assert!(serde_json::from_str::<MyStruct>(s).is_err());
}

Thanks

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