daily pastebin goal
58%
SHARE
TWEET

Untitled

a guest Jan 24th, 2019 61 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. extern crate serde;
  2. #[macro_use]
  3. extern crate serde_derive;
  4. extern crate serde_json;
  5.  
  6. use serde_json::Value;
  7. use std::collections::HashMap;
  8.  
  9. #[derive(Serialize, Deserialize, Debug, Clone)]
  10. pub struct MyStruct {
  11.     custom: std::collections::HashMap<String, Value>,
  12. }
  13.  
  14. fn main() {
  15.     let instance: MyStruct = serde_json::from_str(
  16.         r#"{"custom": { "a":12345, "b":"213", "c":true, "object_field": {} }}"#,
  17.     )
  18.     .unwrap();
  19.  
  20.     println!("{:?}", instance.custom.to_string_string_map());
  21. }
  22.  
  23. trait ToStringStringMap {
  24.     fn to_string_string_map(&self) -> HashMap<String, String>;
  25. }
  26.  
  27. impl ToStringStringMap for HashMap<String, Value> {
  28.     fn to_string_string_map(&self) -> HashMap<String, String> {
  29.         self.iter()
  30.             .map(|(k, v)| {
  31.                 let v = match v.clone() {
  32.                     e @ Value::Number(_) | e @ Value::Bool(_) => e.to_string(),
  33.                     Value::String(s) => s,
  34.                     _ => {
  35.                         println!(r#"Warning : Can not convert field : "{}'s value to String, It will be set to empty string."#, k);
  36.                         "".to_string()
  37.                     }
  38.                 };
  39.  
  40.                 (k.clone(), v)
  41.             })
  42.             .collect()
  43.     }
  44. }
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