我正在将数据解析为:
struct Data {
field1: Option<f32>,
field2: Option<u64>,
// more ...
}
问题是我的输入数据格式将Rust中的None
格式设置为“ n/a
”。
如何告诉Serde,Option<T>
应该是特定字符串None
的{{1}},而不是错误?我们可以假设这不适用于n/a
。
这不是与How to deserialize "NaN" as `nan` with serde_json?相同的问题,因为这是根据特殊值创建String
,而我的问题是根据特殊值创建f32
。它也不是How to transform fields during deserialization using Serde?,因为它仍然涉及特定类型。
答案 0 :(得分:3)
您可以编写自己的反序列化函数来处理这种情况:
use serde::de::Deserializer;
use serde::Deserialize;
// custom deserializer function
fn deserialize_maybe_nan<'de, D, T: Deserialize<'de>>(
deserializer: D,
) -> Result<Option<T>, D::Error>
where
D: Deserializer<'de>,
{
// we define a local enum type inside of the function
// because it is untagged, serde will deserialize as the first variant
// that it can
#[derive(Deserialize)]
#[serde(untagged)]
enum MaybeNA<U> {
// if it can be parsed as Option<T>, it will be
Value(Option<U>),
// otherwise try parsing as a string
NAString(String),
}
// deserialize into local enum
let value: MaybeNA<T> = Deserialize::deserialize(deserializer)?;
match value {
// if parsed as T or None, return that
MaybeNA::Value(value) => Ok(value),
// otherwise, if value is string an "n/a", return None
// (and fail if it is any other string)
MaybeNA::NAString(string) => {
if string == "n/a" {
Ok(None)
} else {
Err(serde::de::Error::custom("Unexpected string"))
}
}
}
}
然后,您可以使用#[serde(default, deserialize_with = "deserialize_maybe_nan")]
标记字段以使用此功能而不是默认功能:
#[serde(Deserialize)]
struct Data {
#[serde(default, deserialize_with = "deserialize_maybe_nan")]
field1: Option<f32>,
#[serde(default, deserialize_with = "deserialize_maybe_nan")]
field2: Option<u64>,
// more ...
}
文档中的更多信息: