Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserialize using FromStr #1032

Closed
spease opened this issue Sep 2, 2017 · 2 comments
Closed

Deserialize using FromStr #1032

spease opened this issue Sep 2, 2017 · 2 comments

Comments

@spease
Copy link

spease commented Sep 2, 2017

Might be a repeat of some of #553, but I felt this was important enough to call out.

Currently there's a lot of boilerplate code required to deserialize something that already implements FromStr. It would be nice if there were a tag that could be used to specify the use of FromStr or other From trait so this boilerplate isn't needed. Perhaps it should be automatic based on which FromStr/From traits are implemented for that type - although I don't know if this is possible, this would probably be the most intuitive.

Example:

struct LVMDate(chrono::NaiveDate);

impl std::str::FromStr for LVMDate {
  type Err = chrono::format::ParseError;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    Ok(LVMDate(chrono::NaiveDate::parse_from_str(s, "%Y/%m/%d")?))
  }
}
impl<'de> serde::de::Deserialize<'de> for LVMDate {
  fn deserialize<D: serde::de::Deserializer<'de>>(deserializer: D) -> Result<LVMDate, D::Error> {
    deserializer.deserialize_str(LVMDateVisitor)
  }
}

struct LVMDateVisitor;

impl<'de> serde::de::Visitor<'de> for LVMDateVisitor {
  type Value = LVMDate;

  fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
    formatter.write_str("A date in the format YYYY/MM/DD")
  }

  fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> {
    use std::str::FromStr;
    Self::Value::from_str(value).map_err(serde::de::Error::custom)
  }
}
@dtolnay
Copy link
Member

dtolnay commented Sep 3, 2017

As you suggested, let's track this in #553. I don't think this case is so overwhelmingly common that it deserves its own attribute. Hopefully what we come up with in #553 will be ergonomic and more general.

There is another issue here -- customizing the message you get when a type fails to deserialize. Like in your code you have "a date in the format YYYY/MM/DD". I filed #1034 to follow up.

@dtolnay dtolnay closed this as completed Sep 3, 2017
@spease
Copy link
Author

spease commented Sep 3, 2017

Thanks :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Development

No branches or pull requests

2 participants