[][src]Derive Macro serde_with::DeserializeFromStr


Deserialize value by using it's 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 a 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.


This example is not tested
use std::str::FromStr;

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
            .ok_or_else(|| "Missing first value".to_string())?
            .map_err(|err: ParseIntError| err.to_string())?;
        let bool = parts
            .ok_or_else(|| "Missing second value".to_string())?
            .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);