SHARE
TWEET

Untitled

a guest Jun 25th, 2019 53 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. use serde_derive::{Deserialize, Serialize};
  2.  
  3. #[derive(Deserialize, Debug)]
  4. pub struct RequestA {
  5.     pub a: String,
  6. }
  7.  
  8. #[derive(Deserialize, Debug)]
  9. pub struct RequestB {
  10.     pub b: String,
  11. }
  12.  
  13. #[derive(Deserialize, Debug)]
  14. #[serde(deny_unknown_fields)]
  15. pub struct RequestType<T> {
  16.     pub id: u64,
  17.     pub params: T,
  18. }
  19.  
  20. #[derive(Deserialize, Debug)]
  21. #[serde(tag = "method", rename_all = "lowercase")]
  22. pub enum Request {
  23.     RequestA(RequestType<RequestA>),
  24.     RequestB(RequestType<RequestB>),
  25. }
  26.  
  27. #[derive(Serialize, Debug)]
  28. pub struct ResponseA {
  29.     pub a: String,
  30. }
  31.  
  32. #[derive(Serialize, Debug)]
  33. pub struct ResponseB {
  34.     pub b: String,
  35. }
  36.  
  37. #[derive(Serialize, Debug)]
  38. pub struct ResponseType {
  39.     pub id: u64,
  40.     pub result: Response,
  41. }
  42.  
  43. #[derive(Serialize, Debug)]
  44. pub enum Response {
  45.     ResponseA(ResponseA),
  46.     ResponseB(ResponseB),
  47. }
  48.  
  49. fn main() {
  50.     let request_str = r#"
  51.         {
  52.             "id": 0,
  53.             "method": "requesta",
  54.             "params": {
  55.                 "a": "foo"
  56.             }
  57.         }"#;
  58.     let request: Request = serde_json::from_str(&request_str).unwrap();
  59.    
  60.     let result = match request {
  61.         Request::RequestA(_request) => Response::ResponseA(ResponseA { a: "bar".to_string() }),
  62.         Request::RequestB(_request) => Response::ResponseB(ResponseB { b: "baz".to_string() }),
  63.     };
  64.    
  65.     let response_id = 0; // request.id
  66.    
  67.     let response = ResponseType {
  68.         id: response_id,
  69.         result,
  70.     };
  71.  
  72.     let response_str = serde_json::to_string(&response).unwrap();
  73.  
  74.     println!("{}", response_str);
  75.     // should be {"id":0,"result":{"a":"bar"}}
  76.     // is actually {"id":0,"result":{"ResponseA":{"a":"bar"}}}
  77. }
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