bson-rust: ObjectId (de)serialization problem

ObjectId fails to deserialize with serde_qs after #220

    use bson::oid::ObjectId;
    let oid1 = ObjectId::from_str("60c2c48f0096ee4d0025cc0c")?;
    let str = serde_qs::to_string(&oid1)?;
    dbg!((&oid1, &str));
    let oid2: ObjectId = serde_qs::from_str(&str)?;
    dbg!(&oid2);
  • before (bson = { git = "https://github.com/mongodb/bson-rust", rev = "99b50d0" })
[allnet/src/main.rs:44] (&oid1, &str) = (
    ObjectId(60c2c48f0096ee4d0025cc0c),
    "%24oid=60c2c48f0096ee4d0025cc0c",
)
[allnet/src/main.rs:46] &oid2 = ObjectId(60c2c48f0096ee4d0025cc0c)
  • after (bson = { git = "https://github.com/mongodb/bson-rust", rev = "5f17b3d" })
[allnet/src/main.rs:44] (&oid1, &str) = (
    ObjectId(60c2c48f0096ee4d0025cc0c),
    "%24oid=60c2c48f0096ee4d0025cc0c",
)
Error: failed with reason: cannot deserialize primitive at the top level.Try deserializing into a struct.

(i’m using serde_qs inside thin wrapper to handle forms / query parameters in Rocket framework)

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (4 by maintainers)

Most upvoted comments

Hi @univerz, thanks for filing this issue! The problem you’re encountering is due to the fact that serde_qs only supports structs, maps, and enums at the top level. While our previous implementation of Deserialize for ObjectId treated an ObjectId as a map, the changes in the commit you referenced updated this implementation to deserialize from multiple formats. To fix the error you’re encountering, I’d recommend nesting the ObjectId in a struct. You can use the serialize_object_id_as_hex_string serde helper added in https://github.com/mongodb/bson-rust/commit/b55e958e4de10350b67b7d409ff1160c9bc742cb to get the hex string representation of the ObjectId in your query string:

#[derive(Serialize, Deserialize)]
struct Oid {
	#[serde(serialize_with = "serialize_object_id_as_hex_string")]
	oid: ObjectId,
}

Let us know if you encounter any further issues!

Your solution was included in 2.0.0-beta.3, see #289. Thanks so much for helping out with this!

Going to close this out now; to track the remaining work needed to match rmp_serde, please follow RUST-888.