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

标签 rust serde

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

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

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

或者
{
    “foo”: “bar”,
}

IE。 语音是可选的,可以是字符串或字符串数​​组。

我可以使用以下方法处理反序列化字符串/字符串数组:
#[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>>
}

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

但是将所有内容组合在一起根本行不通。看来 deserialize_with 选项类型下无法正常使用。有人可以建议最简单,最简单的方法来实现此方法(serde可能非常复杂,我见过一些疯狂的东西:))?

最佳答案

尝试对speech字段使用Enum类型:

#[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

关于rust - 如何在Rust(使用serde)中反序列化可选的json参数,该参数可以是字符串或字符串数​​组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62031397/

相关文章:

rust - 我如何告诉 Cargo 检查本地目录是否有替换依赖项并使用它?

rust - 将临时 git 依赖项修补到特定版本

rust - 取决于特征是否被实现的函数行为

json - 使用Serde反序列化嵌套JSON结构时的“invalid type: map, expected a sequence”

hash - 如何从可哈希的库中创建一个不可哈希的、类 C 的枚举?

macros - 修复 "no rules expected the token"宏错误

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

json - 如何将Serde与具有不同对象的JSON数组一起使用,以获取成功和错误?

rust - 为什么我要获得 “Cannot Derive Macro In This Scope”?

rust - 使用多个模式结构反序列化 XML