如何在 Rust 中反序列化(使用 serde)可选 json 参数,可以是字符串或字符串数​​组

2024-03-07

我是 Rust 新手,我正在尝试使用 serde 库反序列化 JSON 数据。 我有以下 JSON 结构:

{
    “foo”: “bar”,
    “speech”: “something”
}

or

{
    “foo”: “bar”,
    “speech”: [“something”, “something else”]
}

or

{
    “foo”: “bar”,
}

I.e. speech是可选的,它可以是字符串或字符串数​​组。

我可以使用以下方法处理反序列化字符串/字符串数组:

#[derive(Debug, Serialize, Deserialize)]
   struct foo {
   pub foo: String,
   #[serde(deserialize_with = "deserialize_message_speech")]
   speech: Vec<String>
}

我还可以使用以下方法处理反序列化可选字符串/字符串数组属性:

#[derive(Debug, Serialize, Deserialize)]
struct foo {
   pub foo: String,
   #[serde(skip_serializing_if = "Option::is_none")]
   speech: Option<Vec<String>>
}

or

struct foo {
   pub foo: String,
   #[serde(skip_serializing_if = "Option::is_none")]
   speech: Option<String>
}

但将它们结合在一起根本行不通。它似乎反序列化不能正常工作Option类型。有人可以建议最简单和最简单的方法来实现这个(serde 可能非常复杂,我见过一些疯狂的东西:))?


尝试使用 Enum 类型speech field:

#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum Speech {
    Str(String),
    StrArray(Vec<String>),   
}

#[derive(Debug, Serialize, Deserialize)]
   struct foo {
   pub foo: String,
   speech: Option<Speech>,
}

枚举是 Rust 中表示变体类型的首选方法。看https://serde.rs/enum-representations.html https://serde.rs/enum-representations.html了解更多详情。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Rust 中反序列化(使用 serde)可选 json 参数,可以是字符串或字符串数​​组 的相关文章

随机推荐