Deserialize a field that sometimes has quotations around the value

70 Views Asked by At

I'm consuming a JSON API that looks like this:

{
    "timestamp": 1650057633185497
}

This will work fine with a struct that looks like:

#[derive(Clone, Debug, Deserialize)]
pub struct Msg {
    pub timestamp: i64
}

Unfortunately the server sometimes sends:

{
    "timestamp": "1650057633185497"
}

If this was the only way it sent it, I could do:

#[derive(Clone, Debug, Deserialize)]
pub struct Msg {
    #[serde(with = "serde_with::rust::display_fromstr")]
    pub timestamp: i64
}

But if it's sometimes one, sometimes the other, leaving the struct in one or the other form will not work when the other variant arrives.

Is there a way to tell Serde to just make an i64 out of it regardless of whether it has the quotation marks?

0

There are 0 best solutions below