time-rs / time

The most used Rust library for date and time handling.
https://time-rs.github.io
Apache License 2.0
1.09k stars 273 forks source link

Deserializing missing field into `Option<OffsetDateTime>` with `#[serde(with = "iso8601::option")]` is failing #518

Closed legas7 closed 1 year ago

legas7 commented 1 year ago

Deserializing missing field into option fails with panic: [example](https://www.rustexplorer.com/b#%2F*%0A%5Bdependencies%5D%0Atime%20%3D%20%7B%20version%20%3D%20%220.3.14%22%2C%20features%20%3D%20%5B%22serde%22%2C%20%22serde-well-known%22%5D%20%7D%0Aserde%20%3D%20%7B%20version%20%3D%20%221.0.145%22%2C%20features%20%3D%20%5B%22derive%22%5D%20%7D%0Aserde_json%20%3D%20%221.0%22%0A*%2F%0A%0Ause%20serde%3A%3ADeserialize%3B%0Ause%20time%3A%3AOffsetDateTime%3B%0Ause%20serde_json%3A%3Ajson%3B%0Ause%20time%3A%3Aformat_description%3A%3Awell_known%3A%3AIso8601%3B%0A%0A%0A%23%5Bderive(Deserialize%2C%20PartialEq%2C%20Eq%2C%20Debug)%5D%0Apub%20struct%20ExportParameters%20%7B%0A%20%20%20%20%23%5Bserde(with%20%3D%20%22time%3A%3Aserde%3A%3Aiso8601%3A%3Aoption%22)%5D%0A%20%20%20%20pub%20trigger_point%3A%20Option%3COffsetDateTime%3E%2C%0A%20%20%20%20%23%5Bserde(with%20%3D%20%22time%3A%3Aserde%3A%3Aiso8601%22)%5D%0A%20%20%20%20pub%20start_time%3A%20OffsetDateTime%0A%7D%0A%0Afn%20main()%20%7B%0A%20%20%20%20let%20raw_timestamp%20%3D%20%222021-02-24T03%3A00%3A00Z%22%3B%0A%20%20%20%20let%20raw_input%20%3D%20json!(%7B%20%0A%20%20%20%20%20%20%20%20%22start_time%22%3A%20raw_timestamp%0A%20%20%20%20%7D)%3B%0A%0A%20%20%20%20let%20input%3A%20ExportParameters%20%3D%20serde_json%3A%3Afrom_value(raw_input).unwrap()%3B%0A%0A%20%20%20%20let%20expected%20%3D%20ExportParameters%20%7B%0A%20%20%20%20%20%20%20%20trigger_point%3A%20None%2C%0A%20%20%20%20%20%20%20%20start_time%3A%20OffsetDateTime%3A%3Aparse(raw_timestamp%2C%20%26Iso8601%3A%3ADEFAULT).unwrap()%20%0A%20%20%20%20%7D%3B%0A%0A%20%20%20%20assert_eq!(input%2C%20expected)%0A%7D).

#[derive(Deserialize, PartialEq, Eq, Debug)]
pub struct ExportParameters {
    #[serde(with = "time::serde::iso8601::option")]
    pub trigger_point: Option<OffsetDateTime>,
}

Shouldn't deserialization into Option\<T> work without #[serde(default)]?

jhpratt commented 1 year ago

Saying this panics is extremely misleading. The panic is in the code you wrote, not in time.

I am not aware of any way to have this work without #[serde(default)]. This has been asked before with the same answer.

legas7 commented 1 year ago

Did not know that's known issue and also did not want to mislead anyone. Thanks for your work!