Skip to main content

Crate specta_serde

Crate specta_serde 

Source
Expand description

Serde support for Specta

This crate parses #[serde(...)] attributes and applies the necessary transformations to your types. This is possible because the Specta macro crate stores discovered macro attributes in the [specta::DataType] definition of your type.

For specific attributes, refer to Serde’s official documentation.

§Usage

§Transform a TypeCollection in-place

use specta::TypeCollection;
use specta_serde::{apply, SerdeMode};

let mut types = TypeCollection::default();
// Add your types...

// For serialization only
apply(&mut types, SerdeMode::Serialize)?;

// For deserialization only
apply(&mut types, SerdeMode::Deserialize)?;

// For both (uses common attributes, skips mode-specific ones)
apply(&mut types, SerdeMode::Both)?;

§Transform a single DataType

use specta::DataType;
use specta_serde::{apply_to_dt, SerdeMode};

let dt = DataType::Primitive(specta::datatype::Primitive::String);
let transformed = apply_to_dt(dt, SerdeMode::Serialize)?;

§Understanding SerdeMode

  • SerdeMode::Serialize: Apply transformations for serialization (Rust → JSON/etc). Respects skip_serializing, rename_serialize, etc.

  • SerdeMode::Deserialize: Apply transformations for deserialization (JSON/etc → Rust). Respects skip_deserializing, rename_deserialize, etc.

  • SerdeMode::Both: Apply transformations that work for both directions.

    • Uses common attributes like rename, rename_all, skip
    • Only skips fields/types that are skipped in BOTH modes
    • Ignores mode-specific attributes unless they match in both modes
    • Useful when you want a single type definition for bidirectional APIs

Enums§

EnumRepr
Serde representation of an enum. Refer to the Serde documentation for more information.
Error
Detected a type which Serde is unable to export.
SerdeMode
Specifies whether to apply serde transformations for serialization or deserialization

Functions§

apply
Apply Serde attributes to a TypeCollection in-place.
apply_serde_transformations
Apply serde transformations to a DataType for the specified mode
apply_to_dt
Apply Serde attributes to a single DataType.
get_enum_repr
Get the enum representation from serde attributes
is_field_flattened
Check if a field has the #[serde(flatten)] attribute