Skip to content

Commit 5f17b3d

Browse files
RUST-602 Deserialize ObjectId from a hex string (#220)
1 parent 99b50d0 commit 5f17b3d

File tree

2 files changed

+28
-8
lines changed

2 files changed

+28
-8
lines changed

src/de/serde.rs

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -30,14 +30,19 @@ impl<'de> Deserialize<'de> for ObjectId {
3030
where
3131
D: de::Deserializer<'de>,
3232
{
33-
deserializer.deserialize_map(BsonVisitor).and_then(|bson| {
34-
if let Bson::ObjectId(oid) = bson {
35-
Ok(oid)
36-
} else {
37-
let err = format!("expected objectId extended document, found {}", bson);
38-
Err(de::Error::invalid_type(Unexpected::Map, &&err[..]))
39-
}
40-
})
33+
deserializer
34+
.deserialize_any(BsonVisitor)
35+
.and_then(|bson| match bson {
36+
Bson::String(oid) => ObjectId::with_string(&oid).map_err(de::Error::custom),
37+
Bson::ObjectId(oid) => Ok(oid),
38+
_ => {
39+
let err = format!(
40+
"expected objectId extended document or hex string, found {}",
41+
bson
42+
);
43+
Err(de::Error::invalid_type(Unexpected::Map, &&err[..]))
44+
}
45+
})
4146
}
4247
}
4348

src/tests/serde.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::{
55
compat::u2f,
66
doc,
77
from_bson,
8+
oid::ObjectId,
89
spec::BinarySubtype,
910
tests::LOCK,
1011
to_bson,
@@ -558,3 +559,17 @@ fn test_de_db_pointer() {
558559

559560
assert_eq!(foo.db_pointer, db_pointer.clone());
560561
}
562+
563+
#[test]
564+
fn test_de_oid_string() {
565+
let _guard = LOCK.run_concurrently();
566+
567+
#[derive(Debug, Deserialize)]
568+
struct Foo {
569+
pub oid: ObjectId,
570+
}
571+
572+
let foo: Foo = serde_json::from_str("{ \"oid\": \"507f1f77bcf86cd799439011\" }").unwrap();
573+
let oid = ObjectId::with_string("507f1f77bcf86cd799439011").unwrap();
574+
assert_eq!(foo.oid, oid);
575+
}

0 commit comments

Comments
 (0)