我正在尝试使用serde反序列化如下所示的JSON数据:
{
"item1": "Foo",
"item2": "Bar",
"item3": "Baz",
"item4": null,
"item5": null,
"description1": "something",
"description2": "another thing",
"description3": "one more thing",
"description4": null,
"description5": null
}
可以假设只有5个项目,并且字段将始终存在(但可能为null)。
我希望将其放入
Vec<Item>
中struct Item {
name: String,
description: String,
}
我知道我可以
#[derive(Deserialize)]
并为名称字段加上别名,但是我不确定如何处理将编号的项目转换为列表。如何在Serde中处理这样的案件?
最佳答案
考虑将serde_json::from_str解析为serde_json::Value
然后应用您的特定用例所需的转换。
#[derive(Debug)]
struct Item {
name: String,
description: String,
}
fn main() {
let data = r#"
{
"item1": "Foo",
"item2": "Bar",
"item4": null,
"item5": null,
"description1": "something",
"description2": "another thing",
"description3": "one more thing",
"description4": null,
"description5": null
}"#;
let v: Value = serde_json::from_str(data).unwrap();
let mut items = Vec::new();
for idx in 1..6 {
let name = format!("item{}", idx);
let descr = format!("description{}", idx);
if let (Value::String(value), Value::String(descr)) = (&v[name], &v[descr]) {
items.push(Item {
name: value.to_string(),
description: descr.to_string(),
})
}
}
println!("items {:?}", items);
}
关于rust - 使用Serde反序列化编号的项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60573226/