rust - 使用Serde反序列化编号的项目

标签 rust serde

我正在尝试使用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/

相关文章:

linux - 无法加载redis模块,RedisJSON

json - 镍.rs : Receiving JSON data using HTTP POST request - rust keyword clash + fail on JSON null values

serialization - 使用#[serde(untagged)] 和#[serde(with)] 的组合反序列化枚举

rust - 在 Rust 中使用 serde 对包含具有无效 utf-8 字符的路径的 PathBuf 进行编码

http - Rust/Serde/HTTP : Serialize `Option<http::Method>`

rust - 在 Serde 中实现通用长度分隔的十六进制解串器

rust - 如何从 String.split().collect() 返回数据?

rust - Actix Web 的终身问题

rust - 如何指定我想要一个泛型类型来支持 'new'

rust - 为什么在以 `Self: Sized` 为界时不能调用特征对象上的函数?