将整数和字符串反序列化为结构,当输入为整数时失败

时间:2018-10-01 08:29:58

标签: rust serde

我正在尝试编写一个反序列化器,该序列化器可同时用于字符串和整数输入值。但是当输入是整数时失败。

#[derive(Serialize, Queryable, Clone, Debug)]
#[cfg_attr(test, derive(Default))]
pub struct Obj {
    pub id: i32,
    pub name: String,
}

impl<'de> Deserialize<'de> for Obj {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        struct VariantVisitor;

        impl<'de> Visitor<'de> for ObjVisitor {
            type Value = Obj;

            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
                formatter.write_str("valid obj_id")
            }

            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                get_obj(value as i32).ok_or(E::custom("invalid obj id"))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                match get_id(value, "xyz") {
                    Ok(id) => self.visit_i64(id as i64),
                    Err(_) => Err(E::custom("invalid value")),
                }
            }
        }

        deserializer.deserialize_identifier(VariantVisitor)
    }
}

当输入为{'obj': 1}时,反序列化后会得到

  

错误:无效类型:整数1,预期有效的obj_id,

当输入为{'obj': "1"}时,它可以正常工作。

0 个答案:

没有答案