如何将逗号分隔的 JSON 字符串反序列化为单独字符串的向量?
How can I deserialize a comma-separated JSON string as a vector of separate strings?
我想用我自己的一个字段的反序列化器反序列化来自 Rocket with Serde 的传入数据。 tags
字段原本是一个字符串,应该反序列化为Vec<String>
。字符串的格式或多或少是逗号分隔值,对某些字符进行了特殊处理。
我完全不清楚 Serde 的文档如何处理这种情况。 tags_deserialize
的基本结构我刚从documentation.
复制过来的
目前我的代码如下:
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskDataJson {
pub name: String,
pub description: String,
#[serde(deserialize_with = "tags_deserialize")]
pub tags: Vec<String>
}
fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
??? - How do I access the string coming from the response and how do I set it??
}
传入数据的样本是:
{
"name":"name_sample",
"description":"description_sample",
"tags":"tag1,tag2,tag5"
}
这应该导致:
name = "name_sample";
description = "description_sample"
tags = ["tag1", "tag2", "tag5"]
解决方法是将字符串序列 "tag1,tag2,tag3" 反序列化为 String
值,然后将其转换为 Vec
字符串,例如:
fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
let str_sequence = String::deserialize(deserializer)?;
Ok(str_sequence
.split(',')
.map(|item| item.to_owned())
.collect())
}
我想用我自己的一个字段的反序列化器反序列化来自 Rocket with Serde 的传入数据。 tags
字段原本是一个字符串,应该反序列化为Vec<String>
。字符串的格式或多或少是逗号分隔值,对某些字符进行了特殊处理。
我完全不清楚 Serde 的文档如何处理这种情况。 tags_deserialize
的基本结构我刚从documentation.
目前我的代码如下:
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct TaskDataJson {
pub name: String,
pub description: String,
#[serde(deserialize_with = "tags_deserialize")]
pub tags: Vec<String>
}
fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
??? - How do I access the string coming from the response and how do I set it??
}
传入数据的样本是:
{
"name":"name_sample",
"description":"description_sample",
"tags":"tag1,tag2,tag5"
}
这应该导致:
name = "name_sample";
description = "description_sample"
tags = ["tag1", "tag2", "tag5"]
解决方法是将字符串序列 "tag1,tag2,tag3" 反序列化为 String
值,然后将其转换为 Vec
字符串,例如:
fn tags_deserialize<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>
where
D: Deserializer<'de>,
{
let str_sequence = String::deserialize(deserializer)?;
Ok(str_sequence
.split(',')
.map(|item| item.to_owned())
.collect())
}