Serde: Serialize Enum as String?

So I have a struct as below that I will only serialize:

#[derive(Debug, Serialize)]
/// See: https://core.telegram.org/bots/api#sendmessage
struct SendMessage {
    chat_id: i32,
    text: String,
    parse_mode: Option<ParseMode>,
}

And the ParseMode in question is an enum.

#[derive(Debug)]
enum ParseMode {
    Markdown,
    HTML,
}

:bulb: Tip

As you've probably guessed by now, the question is about Telegram bot API's sendMessage method.

I'd like this parse_mode to serialize as a string depending what it is:

  • if it's Markdown then serialize to "parse_mode": "markdown"
  • if it's HTML then serialize to "parse_mode": "html"

That is why I thought it is a good idea to implement a custom serializer because the section about enums only talks about enum variants.

Then I've come across those two sections from the documentations:

And I am totally lost, it's really hard to make sense of it. How serde works is a mystery to me.

As I've told you, I'd like to render a ParseMode as a string? I know this looks like a total burden but can you at least show me where to begin?

Thanks in advance.


Environment

  • rust 1.39.0
  • serde 1.0.104
  • serde_json 1.0.44

An enum variant without any data stored within it already gets serialized as a string, so the only part you're missing is how to make the string's value transform to lowercase. You can use either the rename attribute or the rename_all attribute to do this. The latter is easier, if you know that the variant names will always match the values aside from case.

2 Likes

Thank you @17cupsofcoffee. This greatly solves my problem.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.