Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to deserialize ISO formatted json into Bson::DateTime #472

Closed
Bryson14 opened this issue Apr 5, 2024 · 1 comment
Closed

How to deserialize ISO formatted json into Bson::DateTime #472

Bryson14 opened this issue Apr 5, 2024 · 1 comment
Assignees
Labels

Comments

@Bryson14
Copy link

Bryson14 commented Apr 5, 2024

Versions/Environment

  1. What version of Rust are you using?
  2. What operating system are you using?
  3. What versions of the driver and its dependencies are you using? (Run
    cargo pkgid mongodb & cargo pkgid bson)
  4. What version of MongoDB are you using? (Check with the MongoDB shell using db.version())
  5. What is your MongoDB topology (standalone, replica set, sharded cluster, serverless)?

Describe the bug

A clear and concise description of what the bug is.

The Code I'm using to test this looks like this:

	#[test]
	fn test_bson_datetime_parsing() {
		let dt = bson::DateTime::now();
		let s = dt.to_string();
		let iso = dt.try_to_rfc3339_string().unwrap();
		let doc = doc!{ "time": dt };
		let json = json!({"time": dt});
		println!("df: {dt}, s: {s}, iso: {iso}, doc: {doc}, json: {json}");
		let iso_string = "2024-04-05T19:24:00.408Z";
		let json_str = format!(
			r#"{{
				"time": {{"$date" : {{"$numberLong":"{}"}} }}, "id": "{}"
			}}"#,
			"1674504029491", "390f5f21-631a-463d-88a5-ebc29ca8a6e3"
		);
		let parsed: BsonTester = serde_json::from_str(&json_str).unwrap();
		println!("{}", parsed.time.unwrap().try_to_rfc3339_string().unwrap())
	}
	```
	

But the main issue is that I want the user to be able to see a json object like:
```json
{
    "time": "2024-04-05T19:24:00.408Z"
}

And this could then be deserialized with serde_json automatically with a struct like this:

#[derive(Deserialize, Serialize, Debug)]
	struct BsonTester {
		time: Option<bson::DateTime>,
		id: Option<bson::Uuid>
	}

That way the client doesn have to deal with this mess of $date { $numberLong } when sending data to or from the web server

@abr-egn
Copy link
Contributor

abr-egn commented Apr 9, 2024

I think the bson_datetime_as_rfc3339_string helper will do exactly what you're looking for here 🙂

@abr-egn abr-egn closed this as completed Apr 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants