Failure when using ts_seconds_option with Option<DateTime<Utc> when value missing

33 Views Asked by At

The artifact ts_seconds_option doesn't work when the value is missing in the input data. struct :

use chrono::{DateTime, Utc};
use chrono::serde::ts_seconds_option;
use serde::{Deserialize, Serialize};

#[derive(Serialize, Deserialize)]
pub struct Tariff {
    country_code: String,
    #[serde(with = "ts_seconds_option")]
    start_date_time: Option<DateTime<Utc>>,
    #[serde(with = "ts_seconds_option")]
    end_date_time: Option<DateTime<Utc>>,
    energy_mix: Option<EnergyMix>
}

main.rs (unit test with a struct without start_date_time) :

fn main() {
    let data = r#"
    {
        "country_code": "DE",
        "party_id": "ALL",
        "id": "12",
        "currency": "EUR",
        "elements": [{
          "price_components": [{
            "type": "TIME",
            "price": 2.00,
            "vat": 10.0,
            "step_size": 60
          }]
        }],
        "last_updated": "2015-06-29T20:39:09Z"
    }
    "#;
    let t: Tariff = match serde_json::from_str(data) {
        Ok(it) => it,
        Err(err) => panic!("Problem opening the file: {:?}", err),
    };

Result :

thread 'main' panicked at src/main.rs:25:21: Problem opening the file: Error("missing field 'start_date_time'", line: 16, column: 5)

cargo.toml:

[dependencies] chrono = { version = "0.4.31", features = ["serde"] } serde = { version ="1.0.190", features = ["derive"] } serde_json = "1.0.108"

I try to search over internet but no one seems to have the same problem...

0

There are 0 best solutions below