serde-xml-rs icon indicating copy to clipboard operation
serde-xml-rs copied to clipboard

Empty fields dont use default

Open martinlindhe opened this issue 6 years ago • 3 comments

I expect the following code to populate val with the default value (0) since its an empty tag, instead it gives error panicked at 'called Result::unwrap()on anErr value: expected an integer'

#[test]
fn test_serde_deserialize_empty_field() {

    #[derive(Debug, Deserialize)]
    struct Root {
        id: String,

        #[serde(default)]
        val: u64,
    }

    let s = r##"
        <Root>
            <id>abc</id>
            <val/>
        </Root>
    "##;
    let project: Root = serde_xml_rs::deserialize(s.as_bytes()).unwrap();
    println!("{:#?}", project);
}

martinlindhe avatar Dec 04 '18 03:12 martinlindhe

I worked around the issue with

fn val_deserializer<'de, D>(d: D) -> Result<u64, D::Error>
where
    D: Deserializer<'de>,
{
    let s = String::deserialize(d)?;
    match &s[..] {
        "" => Ok(0),
        _ => Ok(s.parse::<u64>().unwrap()),
    }
}

martinlindhe avatar Dec 04 '18 03:12 martinlindhe

@martinlindhe Were do you have to put this fn val_deserializer()?

kolbma avatar Jul 25 '20 13:07 kolbma

@martinlindhe Were do you have to put this fn val_deserializer()?

Ups. Found it https://serde.rs/field-attrs.html#deserialize_with

kolbma avatar Jul 25 '20 13:07 kolbma