Derive Macro serde_with::DeserializeFromStr

source ·
#[derive(DeserializeFromStr)]
{
    // Attributes available to this derive:
    #[serde_with]
}
Available on crate feature macros only.
Expand description

Deserialize value by using its FromStr implementation

This is an alternative way to implement Deserialize for types, which also implement FromStr by deserializing the type from string. Ensure that the struct/enum also implements FromStr. If the implementation is missing, you will get an error message like

error[E0277]: the trait bound `Struct: std::str::FromStr` is not satisfied

Additionally, FromStr::Err must implement Display as otherwise you will see a rather unhelpful error message

Serialization with Display is available with the matching SerializeDisplay derive.

§Attributes

Attributes for the derive can be specified via the #[serde_with(...)] attribute on the struct or enum. Currently, these arguments to the attribute are possible:

§Example

use std::str::FromStr;

#[derive(DeserializeFromStr)]
struct A {
    a: u32,
    b: bool,
}

impl FromStr for A {
    type Err = String;

    /// Parse a value like `123<>true`
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut parts = s.split("<>");
        let number = parts
            .next()
            .ok_or_else(|| "Missing first value".to_string())?
            .parse()
            .map_err(|err: ParseIntError| err.to_string())?;
        let bool = parts
            .next()
            .ok_or_else(|| "Missing second value".to_string())?
            .parse()
            .map_err(|err: ParseBoolError| err.to_string())?;
        Ok(Self { a: number, b: bool })
    }
}

let a: A = serde_json::from_str("\"159<>true\"").unwrap();
assert_eq!(A { a: 159, b: true }, a);