Serde: Deserialize a type using FromStr

Created on 28 Apr 2017  路  3Comments  路  Source: serde-rs/serde

From IRC:

Is there a way to tell serde to desrialize my struct using it's FromStr implementation?

support

Most helpful comment

Considering how this is such a common pattern, is there not a way to do this with attributes?

All 3 comments

extern crate serde;

use std::str::FromStr;
use serde::{de, Deserialize, Deserializer};

struct S;

impl FromStr for S {
    type Err = String;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        unimplemented!()
    }
}

impl<'de> Deserialize<'de> for S {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
        where D: Deserializer<'de>
    {
        let s = String::deserialize(deserializer)?;
        FromStr::from_str(&s).map_err(de::Error::custom)
    }
}

Considering how this is such a common pattern, is there not a way to do this with attributes?

This is available in _serde_with_ as display_fromstr.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

dtolnay picture dtolnay  路  4Comments

vityafx picture vityafx  路  3Comments

tikue picture tikue  路  4Comments

kleimkuhler picture kleimkuhler  路  3Comments

mwu-tow picture mwu-tow  路  3Comments