1

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?

Herohtar
  • 5,347
  • 4
  • 31
  • 41
Carlos
  • 5,991
  • 6
  • 43
  • 82
  • 1
    @Carlos done! I added it as a new crate: [`serde-this-or-that`](https://crates.io/crates/serde-this-or-that) – rv.kvetch Apr 16 '22 at 15:17
  • @Herohtar I actually tried the approach with an untagged enum, I was surprised to see that it was actually slower than an implementation with a `Visitor` as the accepted answer suggests. If curious i added benchmark code for that [here](https://github.com/rnag/serde-this-or-that/tree/main/benches). – rv.kvetch Apr 16 '22 at 15:21
  • @Herohtar it does seem worse, but it's a lot simpler when you have very deeply nested attributes that you want to bubble up to the top level without writing the nested visitor code – BallpointBen Apr 16 '22 at 17:28
  • @BallpointBen I'm talking about the answer with untagged enums, not the visitor one. Your version is nearly identical, but requires additional calls every time you deserialize something. – Herohtar Apr 16 '22 at 23:17
  • @Herohtar yep, that's what I meant. The untagged version is worse than the visitor version in every way except that it's a lot simpler, conceptually, to implement for complex scenarios – BallpointBen Apr 16 '22 at 23:26
  • @BallpointBen Your original (now deleted) comment had an untagged enum version that implemented TryFrom instead of just using a deserializer. That is what I was referring to, saying it was worse than just implementing the deserializer. I was not talking about the visitor version at all. – Herohtar Apr 16 '22 at 23:39

0 Answers0