JSON serialize struct with date



examples/json/json-serialize-struct-with-date/Cargo.toml
[package]
name = "json-serialize-struct-with-date"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
chrono = { version = "0.4.26", features = ["serde"] }

examples/json/json-serialize-struct-with-date/src/main.rs
use chrono::serde::ts_seconds;
use chrono::{DateTime, Utc};
use serde::Serialize;

// https://docs.rs/chrono/0.4.19/chrono/serde/index.html

#[derive(Debug, Serialize)]
#[allow(dead_code)]
struct Thing {
    name: String,
    number: i8,
    numbers: Vec<i32>,

    #[serde(with = "ts_seconds")]
    now: DateTime<Utc>,
}

fn main() {
    let thing = Thing {
        name: String::from("Foo Bar"),
        number: 42,
        numbers: vec![23, 19],
        now: Utc::now(),
    };
    println!("{:#?}", &thing);
    let serialized = serde_json::to_string(&thing).unwrap();
    println!("{}", serialized);
}

Thing {
    name: "Foo Bar",
    number: 42,
    numbers: [
        23,
        19,
    ],
    now: 2024-07-11T10:19:56.690151283Z,
}
{"name":"Foo Bar","number":42,"numbers":[23,19],"now":1720693196}