Serde: nesting two instances of the same struct?
⚓ Rust 📅 2025-05-14 👤 surdeus 👁️ 13Suppose I have something like
#[derive(serde::Serialize)]
pub struct Instant {
pub at: DateTime,
pub sequence: u64,
}
#[derive(serde::Serialize)]
pub struct History {
pub start: Instant,
pub end: Option<Instant>,
}
Suppose further that, for application-specific reasons, I want the serialized representation to look like (JSON):
{
"start_at": "2025-05-13T01:23:45.6789Z",
"start_sequence": 7,
"end_at": "2024-05-01T00:00:00.0000Z",
"end_sequence": 3671
}
I can achieve this a few ways, including by translating my History to a flatter structure using #[serde(into)] before serializing it, implementing Serialize myself, or not nesting structures in this way. What I'd like, however, is to be able to use #[serde(flatten)] to do this - to flatten the fields of Instant into the representation of History, renaming them in the process. Is this possible?
3 posts - 2 participants
🏷️ rust_feed