Using specific names for a tag and content

In our example, we want to have two fields in a serialized data form: distribution and parameters. In the first field, we want to hold a variant of enumeration, but renamed so that it's in lowercase. In the second field, we'll keep the parameters of the specific variant.

To achieve this, you can write your own Serializer and Deserializer, an approach that we'll explore later in this chapter. For this case, however, we can use the #[serde(tag = "...")] and #[serde(context = "...")] attributes. context can only be used in a pair with tag.

We have added this to our RngRequest:

#[serde(tag = "distribution", content = "parameters", rename_all = "lowercase")]

This attribute specifies the distribution key of the serialized object to hold a variant of the enumeration. The variants of the enumeration move to the parameters field of the serialized object. The last attribute, rename_all, changes the case of the name of a variant. Without renaming, we would be forced to use title case for distributions, such as "Uniform" instead of the tidier "uniform".

Sometimes, a serialized value has to include an object with a dynamic structure. Formats such as JSON support free data structures. I don't like unspecified structures, but we may need them to create services that are compatible with existent services.