serde icon indicating copy to clipboard operation
serde copied to clipboard

Allow integer renames for struct fields

Open AndrewScull opened this issue 3 years ago • 6 comments

Closes #1773 and related to PR #2056.

Extends the serde_rename and alias annotations on struct fields to support integer names. Any struct with an integer name is serialized as a map, similarly to structs with any flattened fields, avoiding the need for changes in existing serializer implementations.

Integer names are typed and serialized based on that type, but deserialization is only based on the integer value because deserializers often don't know the exact type of integers.

There are a few unrelated refactors at the start of the series as I was learning the project, then the bulk of the changes are to represent non-string renames (similar to #2056) and to handle the cases of deserialization.

AndrewScull avatar Apr 28 '22 10:04 AndrewScull

This would be very useful, is there anyway that I could help to move this along if @AndrewScull is too busy?

Progdrasil avatar Oct 12 '22 22:10 Progdrasil

This is very useful for my specific use case, where I have an enum to be serialized with adjacent tags. The tags however, are numbers. The data I want to serialize looks like this:

{
  "op": 8,
  "d": {
    "v": 4,
    "heartbeat_interval" :13750.0
  }
}

This is the code that doesn't work unfortunately:

#[derive(Serialize, Deserialize, Debug)]
#[serde(tag = "op", content = "d")]
pub enum DiscordPayload {
    #[serde(rename = "8")]
    Hello(Hello),
}

It expects an identifier rather than an integer

Error deserializing payload: invalid type: integer `8`, expected variant identifier at line 1 column 7

This change does have a valid use case!

fahimmehraj avatar Oct 29 '22 18:10 fahimmehraj

@frykher see #2056 for the MR pertaining to enums

Progdrasil avatar Dec 20 '22 14:12 Progdrasil

I'd love to see this completed. It would be very useful for CBOR specifications that use integers in maps.

labbott avatar Dec 05 '24 18:12 labbott

As an example of working around this limitation for CBOR encoding, I made this declarative macro to rename the fields to numbers for CTAP2 encoding. You can see it' use in passkey-types::ctap2::make_credential

Progdrasil avatar Dec 05 '24 18:12 Progdrasil

Any updates on this? I am trying to use serde via ciborium to serialize/deserialize CBOR data, and it fails, as serde only supports text values.

larrydewey avatar Apr 02 '25 18:04 larrydewey