Guest User

Untitled

a guest
Apr 23rd, 2018
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.04 KB | None | 0 0
  1. extern crate serde;
  2. #[macro_use]
  3. extern crate serde_derive;
  4. extern crate serde_json;
  5.  
  6. use serde::Deserialize;
  7. use serde::de::Deserializer;
  8.  
  9. static INPUT: &str = r#"{
  10. "post" : {
  11. "id" : "123",
  12. "comments" : [{
  13. "body" : "test body",
  14. "comments": [{
  15. "body": "test body 2",
  16. "comments": ""
  17. }]
  18. }]
  19. }
  20. }"#;
  21.  
  22. #[derive(Serialize, Deserialize, Debug)]
  23. struct InputObject {
  24. post: Post
  25. }
  26.  
  27. #[derive(Serialize, Deserialize, Debug)]
  28. struct Post {
  29. id: String,
  30. comments: Vec<Comments>
  31. }
  32.  
  33. #[derive(Serialize, Deserialize, Debug)]
  34. struct Comments {
  35. body: String,
  36. #[serde(deserialize_with="parse_listing")]
  37. comments: Option<Vec<Comments>>
  38. }
  39.  
  40.  
  41. fn parse_listing<'de, D>(d: D) -> Result<Option<Vec<Comments>>, D::Error>
  42. where D: Deserializer<'de>
  43. {
  44. match Deserialize::deserialize(d) {
  45. Ok(comments) => Ok(Some(comments)),
  46. Err(e) => {
  47. println!("{:?}", e);
  48. Ok(None)
  49. }
  50. }
  51. }
  52.  
  53.  
  54. fn main() {
  55. let input: InputObject = serde_json::from_str(INPUT).unwrap();
  56. println!("{:?}", input);
  57. }
Add Comment
Please, Sign In to add comment