Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- extern crate serde;
- #[macro_use]
- extern crate serde_derive;
- extern crate serde_json;
- use serde_json::Value;
- use std::collections::HashMap;
- #[derive(Serialize, Deserialize, Debug, Clone)]
- pub struct MyStruct {
- custom: std::collections::HashMap<String, Value>,
- }
- fn main() {
- let instance: MyStruct = serde_json::from_str(
- r#"{"custom": { "a":12345, "b":"213", "c":true, "object_field": {} }}"#,
- )
- .unwrap();
- println!("{:?}", instance.custom.to_string_string_map());
- }
- trait ToStringStringMap {
- fn to_string_string_map(&self) -> HashMap<String, String>;
- }
- impl ToStringStringMap for HashMap<String, Value> {
- fn to_string_string_map(&self) -> HashMap<String, String> {
- self.iter()
- .map(|(k, v)| {
- let v = match v.clone() {
- e @ Value::Number(_) | e @ Value::Bool(_) => e.to_string(),
- Value::String(s) => s,
- _ => {
- println!(r#"Warning : Can not convert field : "{}'s value to String, It will be set to empty string."#, k);
- "".to_string()
- }
- };
- (k.clone(), v)
- })
- .collect()
- }
- }
Add Comment
Please, Sign In to add comment