我的自定义字段JSON是动态的,需要解析为具有HashMap如下字段的结构:
#[macro_use]
extern crate serde_derive;
extern crate serde;
extern crate serde_json;
use std::collections::HashMap;
#[derive(Serialize, Deserialize)]
struct MyStruct {
field1: String,
custom: HashMap<String, String>,
}
fn main() {
let json_string = r#"{"field1":"3","custom":{"custom1":"15000","custom2":"60"}}"#;
let my_struct = serde_json::from_str::<MyStruct>(json_string).unwrap();
println!("{}", serde_json::to_string(&my_struct).unwrap());
}
Run Code Online (Sandbox Code Playgroud)
当我的 json 字符串在自定义字段中有字符串字段时,它可以轻松解析为字符串。
但问题是我的 json 字符串是:
let json_string_wrong = r#"{"field1":"3","custom":{"custom1":15000,"custom2":"60"}}"#; // Need to parse this
Run Code Online (Sandbox Code Playgroud)
如何在 serde 中处理此类铸件?
Serde提供serde_json::Value(参考)。它是一个枚举,包含以下数据类型:
pub enum Value {
/// Represents a JSON null value.
Null,
/// Represents a JSON boolean.
Bool(bool),
/// Represents a JSON number, whether integer or floating point.
Number(Number),
/// Represents a JSON string.
String(String),
/// Represents a JSON array.
Array(Vec<Value>),
/// Represents a JSON object.
Object(Map<String, Value>),
}
Run Code Online (Sandbox Code Playgroud)
您可以将serde_json::Value其用作 HashMap 的值类型。可以serde_json::Value使用serde_json::from_value或使用模式匹配从 with 中提取数据。在你的情况下,我会使用模式匹配,因为只有Integer类型会被转换为 a String,其余的都是相同的。
但您需要考虑在反序列化后再添加一个步骤。喜欢
custom,将在反序列化后填充。customas的新结构HashMap<String, String>。HashMap<String, Value>为HashMap<String, String>,实现这个特质可以解决你的问题。
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 empty string."#, k);
"".to_string()
}
};
(k.clone(), v)
})
.collect()
}
}
Run Code Online (Sandbox Code Playgroud)
示例:游乐场
注:Trait 的名字选得不太好,欢迎提出建议。
| 归档时间: |
|
| 查看次数: |
13455 次 |
| 最近记录: |