I am trying to write a deserializer that is able to deserialize i64 both from a JSON numeric and a parsable string.
struct I64Visitor;
impl Visitor<'_> for I64Visitor {
type Value = i64;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("Only numeric strings or i64 can be deserialised to i64")
}
fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E>
where
E: Error,
{
Ok(v)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: Error,
{
let res = i64::from_str(v);
match res {
Ok(r) => Ok(r),
Err(err) => Err(E::custom(format!(
"Cannot decode i64 out of: {}. error: {:?}",
v, err
))),
}
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: Error,
{
self.visit_str(&v)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct TwitterId(pub i64);
scalar!(TwitterId);
impl<'de> Deserialize<'de> for TwitterId {
fn deserialize<D>(deserializer: D) -> Result<TwitterId, D::Error>
where
D: Deserializer<'de>,
{
let int = deserializer.deserialize_i64(I64Visitor)?;
Ok(TwitterId(int))
}
}
Currently it throws the "expecting" error when it encounters the string variant:
invalid type: string "1097211439159365632", expected Only numeric strings or i64 can be deserialized to i64 at line 1 column 22
I have no idea what's wrong