SHARE
TWEET

Untitled

a guest Aug 25th, 2019 54 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use serde::{de, Deserialize, Deserializer};
  2.  
  3. #[derive(Debug, Deserialize)]
  4. struct Foo {
  5.     foo: u32,
  6.     #[serde(deserialize_with = "deserialize_from_str")]
  7.     bar: Bar,
  8. }
  9.  
  10. #[derive(Debug, Deserialize)]
  11. struct Bar {
  12.     foo: String,
  13. }
  14.  
  15. fn deserialize_from_str<'de, T, D>(deserializer: D) -> Result<T, D::Error>
  16. where
  17.     D: Deserializer<'de>,
  18.     T: de::DeserializeOwned,
  19. {
  20.     let data: String = Deserialize::deserialize(deserializer)?;
  21.     serde_json::from_str(&data).map_err(de::Error::custom)
  22. }
  23.  
  24. fn main() {
  25.     let data = r#"
  26.         {
  27.             "foo": 42,
  28.             "bar": "{\"foo\":\"bar\"}"
  29.         }
  30.     "#;
  31.     println!("{:?}", serde_json::from_str::<Foo>(data));
  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