Serde clone deserializer

Hi! Very newbee question!

Is there a way to clone the deserialize param to use it to check if it's already an ObjectId if this is not a string?

fn deserialize_objectid<'de, D>(
    deserializer: D,
) -> Result<ObjectId, D::Error>
    where
        D: Deserializer<'de>,
{
    let s = String::deserialize(deserializer)?;
    ObjectId::with_string(&*s).map_err(|_| {
        serde::de::Error::invalid_type(serde::de::Unexpected::Str(&*s), &"Should be a valid ObjectId")
    })
}

No. By design the Deserializer is consumed as part of the deserializing process.

If you just want to handle something that may be either a String or ObjectId, what about deserializing to a temporary enum?

1 Like

Thanks for your answer!

A tempory enum? Like:

enum ID {
   Str(String),
   Obj(ObjectId),
}

And in the struct:

struct Foo {
  id: ID,
}

It's correct?

Does it work when you run it in your program?

You may also want to check out the examples and documentation on serde's website.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.