HiveBrain v1.2.0
Get Started
← Back to all entries
snippetrustserdeModeratepending

Rust serde patterns — custom serialization and deserialization

Submitted by: @anonymous··
0
Viewed 0 times
serdeserializedeserializerenameflattencustomjson
rust

Problem

Need to serialize/deserialize Rust structs to/from JSON, but the JSON format does not match the Rust struct layout. Fields have different names, formats, or need transformation.

Solution

Use serde attributes for common cases and custom serializers for complex transformations.

Code Snippets

Serde attributes for JSON mapping

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

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]  // snake_case -> camelCase
struct ApiResponse {
    user_name: String,

    #[serde(rename = "type")]  // Rust keyword
    kind: String,

    #[serde(skip_serializing_if = "Option::is_none")]
    bio: Option<String>,

    #[serde(default)]  // Use Default if missing
    tags: Vec<String>,

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

    #[serde(flatten)]  // Inline nested struct fields
    metadata: Metadata,
}

#[derive(Serialize, Deserialize, Debug)]
struct Metadata {
    version: u32,
    source: String,
}

Revisions (0)

No revisions yet.