SHARE
TWEET

Untitled

a guest Jul 18th, 2019 79 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use serde::{de::Error, Deserialize, Deserializer}; // 1.0.94
  2. use serde_json; // 1.0.40
  3.  
  4. #[derive(Debug, Deserialize)]
  5. struct EtheriumTransaction {
  6.     account: Account, // hex
  7.     amount: u64,      // decimal
  8. }
  9.  
  10. #[derive(Debug, PartialEq)]
  11. struct Account(u64);
  12.  
  13. impl<'de> Deserialize<'de> for Account {
  14.     fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
  15.     where
  16.         D: Deserializer<'de>,
  17.     {
  18.         let s: &str = Deserialize::deserialize(deserializer)?;
  19.         // do better hex decoding than this
  20.         u64::from_str_radix(&s[2..], 16)
  21.             .map(Account)
  22.             .map_err(D::Error::custom)
  23.     }
  24. }
  25.  
  26. fn main() {
  27.     let raw = r#"{"account": "0xDEADBEEF", "amount": 100}"#;
  28.     let transaction: EtheriumTransaction =
  29.         serde_json::from_str(raw).expect("Couldn't derserialize");
  30.     assert_eq!(transaction.amount, 100);
  31.     assert_eq!(transaction.account, Account(0xDEAD_BEEF));
  32. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top