Skip to main content

SerializeShape

Derive Macro SerializeShape 

Source
#[derive(SerializeShape)]
{
    // Attributes available to this derive:
    #[serde]
    #[serde_shape]
}
Available on crate feature derive only.
Expand description

Derives SerializeShape from Serde serialization metadata.

Use this macro when a type’s emitted output shape should be reflected from the same metadata that Serde uses for serialization. The generated implementation records the serialization-side names, shape graph, and Serde field/container metadata.

Use #[serde_shape(serialize_with = "path")] on a container, variant, or field to override an opaque or foreign representation. The function must accept &mut SerializeShapeContext and return a ShapeRef. Generic hooks can replace inferred bounds with #[serde_shape(bound(serialize = "T: SerializeShape"))] on the container.

§Example

use serde_shape::SerializeDefinitionKind;
use serde_shape::SerializeShape;

#[derive(SerializeShape)]
#[serde(rename = "api-response", rename_all = "camelCase")]
struct Response {
    request_id: u64,
    #[serde(skip_serializing_if = "Option::is_none")]
    next_page: Option<String>,
}

let graph = Response::serialize_shape();
let definition = graph.root_definition().unwrap();

let SerializeDefinitionKind::Struct(shape) = &definition.kind else {
    panic!("Response should produce a struct shape");
};

assert_eq!(definition.type_name.name, "api-response");
assert_eq!(shape.fields[0].name, "requestId");
assert_eq!(shape.fields[1].name, "nextPage");
assert!(shape.fields[1].skip_if.is_some());

Derives serde_shape::SerializeShape from Serde serialization metadata.