'Deserializing adjacently tagged data with special characters

I have JSON data that I need to deserialize, where the format is

[
  {
    "tag": "path\like\string",
    "data": [{"fieldA": 1}, {"fieldA": 2}]
  },
  {
    "tag": "another\path\like\string",
    "data": [{"fieldA": 3, "fieldB": "some string"}, {"fieldA": 4, "fieldB": "some string"}]
  },
  ...
]

Some searching lead me to this page about Adjacently tagged data on the serde docs page under "Enum Representation" which looks like it would fit my use case perfectly. The only problem is that when structuring my enum, the enum variant name must match that name inside the tag field which I can't do in this case because the tag field contains special characters.

Is there anyway I can do something like this using serde

enum Data {
    VariantA(Vec<...>),
    VariantB(Vec<...>)
}

with my JSON data? I am not able to change the format of the JSON data currently.



Solution 1:[1]

I added variant renaming after configuring my enum to be serialized with adjacent tagging. Thanks to @Masklinn for pointing this out to me.

So with the JSON data

[
  {
    "tag": "path\like\string",
    "data": [{"fieldA": 1}, {"fieldA": 2}]
  },
  {
    "tag": "another\path\like\string",
    "data": [{"fieldA": 3, "fieldB": "some string"}, {"fieldA": 4, "fieldB": "some string"}]
  },
  ...
]

The corresponding enum should look like this:

use serde::Deserialize;

#[derive(Debug, Deserialize)]
#[serde(tag = "tag", content = "data")]
enum Data {
    #[serde(rename = "path\like\string")]
    VariantA(Vec<...>),

    #[serde(rename = "another\path\like\string")]
    VariantB(Vec<...>),
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1