Cannot restore date from date.json

// edition = "2024"

// [dependencies]
// chrono ={ version="0.4.40" , features= ["serde" ]  }
// serde = { version = "1.0.219", features = ["derive"] }
// serde_json = "1.0.140"


const DT_FMT_:&str= "%e.%m.%Y %H:%M:%S %a" ;

use std::{/* fmt::Debug, */ fs};
use chrono::{/* format::DelayedFormat, */ DateTime, /* Local,  */  Utc  };
use serde::{Serialize, Deserialize};

////////////////////////////////////////////////////////
#[derive( Serialize,  Deserialize  , Debug )]
struct JsnStct {
    // #[serde(with = "local_datetime_format")]
    date_: /* DelayedFormat<  */ DateTime< /* Local */  Utc >    ,
    // note_: String,
}
////////////////////////////////////////////////////////
// fn save_evns(_evns_:&str /* &Evn_ */, _path_: &str) -> std::io::Result<()> {
//     let jsn_ = serde_json::to_string_pretty(_evns_)?;
//     fs::write(_path_, jsn_)
// }
////////////////////////////////////////////////////////
fn dt_jsn(_path_: &str) -> std::io::Result<JsnStct> {
    let dt_jsn_ = fs::read_to_string(_path_)?;
    Ok(serde_json::from_str(&dt_jsn_)?)
}
////////////////////////////////////////////////////////
fn main() -> Result<(), Box<dyn std::error::Error>> {

    let now_=chrono::Local:: now ( ) . format ( DT_FMT_/* "%e.%m.%Y %H:%M:%S %a" */ ) ; //  .to_rfc2822() 
    println!("{now_}") ; // dbg!(&now_);

    // Create sample data
    let dt_jsn_ = vec![
        JsnStct { date_: /* Local */  Utc::now()/* .format(DT_FMT_) */ },
        JsnStct { date_: /* Local */  Utc::now()/* .format(DT_FMT_) */ },
        JsnStct { date_: /* Local */  Utc::now()/* .format(DT_FMT_) */ },      
    ];

    // Serialize to JSON
    let dt_serde_jsn_serzed_ = serde_json::to_string_pretty(&dt_jsn_)?;
    println!("\nSerialized JSON:\n{}", dt_serde_jsn_serzed_);

    let path_:&str="dt_serde.json";  // save_evns(&evns_, path_/* "evn.json" */).unwrap(); 
    let _ = fs::write(path_, &dt_serde_jsn_serzed_/* jsn_ */) ;

    // Deserialize back from variable
    println!("\nDeserialized dates (var):");
    let dt_serde_jsn_deserzed_var_: Vec<JsnStct> = serde_json::from_str(&dt_serde_jsn_serzed_)?;
    for _jsn_date_ in dt_serde_jsn_deserzed_var_ {
        println!("Date: {} ", _jsn_date_.date_ /* .format(DT1_)  */ /*  , _evn_.note_ */  );
    }

    // Deserialize from file
    println!("\nDeserialized dates (file):");
    let dt_serde_jsn_deserzed_file_ = dt_jsn(path_ ).unwrap();
    println!("{:?}", dt_serde_jsn_deserzed_file_) ;// dbg!(&loaded_data); 
  
    Ok(())
}


(Playground)

Output:

28.04.2025 08:58:42 Mon

Serialized JSON:
[
  {
    "date_": "2025-04-28T08:58:42.119182846Z"
  },
  {
    "date_": "2025-04-28T08:58:42.119183466Z"
  },
  {
    "date_": "2025-04-28T08:58:42.119183656Z"
  }
]

Deserialized dates (var):
Date: 2025-04-28 08:58:42.119182846 UTC 
Date: 2025-04-28 08:58:42.119183466 UTC 
Date: 2025-04-28 08:58:42.119183656 UTC 

Deserialized dates (file):

Errors:

   Compiling playground v0.0.1 (/playground)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 1.64s
     Running `target/debug/playground`

thread 'main' panicked at src/main.rs:61:54:
called `Result::unwrap()` on an `Err` value: Custom { kind: InvalidData, error: Error("invalid type: map, expected an RFC 3339 formatted date and time string", line: 2, column: 2) }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Your are serializing a vector of structs, but attemp to deserialize that as a single struct.

1 Like