Skip to content
This repository was archived by the owner on Jul 9, 2023. It is now read-only.
This repository was archived by the owner on Jul 9, 2023. It is now read-only.

Derive macros to serialize and deserialize struct as an array of values #3

@dtolnay

Description

@dtolnay

By default, Serde will serialize a struct to JSON as a JSON map like {"s":"","i":0,"b":true}. In some cases it can be preferable to serialize as a JSON array like ["",0,true]. Serde serializes tuple structs like this, but then we lose the field names when working with the type in Rust code.

I would like there to be derive macros Serialize_tuple and Deserialize_tuple that let me write an ordinary braced struct with named fields but serialize it as if it were a tuple struct.

#[derive(Serialize_tuple, Deserialize_tuple)]
struct T {
    s: String,
    i: i32,
    b: bool,
}

See serde_repr as an existing example of an independent special-purpose derive macro for Serde traits.

// generated code

impl serde::Serialize for T {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        #[derive(serde::Serialize)]
        #[serde(rename = "T")]
        struct Helper<'a>(&'a String, &'a i32, &'a bool);

        let helper = Helper(&self.s, &self.i, &self.b);
        serde::Serialize::serialize(&helper, serializer)
    }
}

impl<'de> serde::Deserialize<'de> for T {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        #[derive(serde::Deserialize)]
        #[serde(rename = "T")]
        struct Helper(String, i32, bool);

        let helper: Helper = serde::Deserialize::deserialize(deserializer)?;
        Ok(T {
            s: helper.0,
            i: helper.1,
            b: helper.2,
        })
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions