0

The following is an example from actix-web's docs on how to deserialize Query data into a struct:

use actix_web::{get, web, App, HttpServer};
use serde::Deserialize;

#[derive(Deserialize)]
struct Info {
    username: String,
}

// this handler gets called if the query deserializes into `Info` successfully
// otherwise a 400 Bad Request error response is returned
#[get("/")]
async fn index(info: web::Query<Info>) -> String {
    format!("Welcome {}!", info.username)
}

I'm trying to get it working when one of the types inside the struct is an enum:

#[derive(serde::Deserialize, serde::Serialize, Debug)]
struct TweetParams {
    page: u32,
    timeframe: Timeframe,
}

#[derive(serde::Deserialize, serde::Serialize, Debug)]
enum Timeframe {
    Hour,
    Four,
    Day,
    Week,
    Month,
}

However, I'm getting the following error:

[2021-06-01T15:15:47Z DEBUG actix_web::middleware::logger] Error in response: Deserialize(Error("unknown variant `popularity`, expected one of `Popularity`, `Retweets`, `Likes`, `Replies`, `Time`"))

Clearly it can't match "Popularity" with "popularity". I'd like to fix the error on the backend, rather than changing capitalization on the front-end. What would be the best way to achieve that?

The only option I was able to come up with is writing a custom deserialization trait which is way over my head as a beginner. Are there other, simpler ways to do it, or should I bite the bullet?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
ilmoi
  • 1,994
  • 2
  • 21
  • 45

0 Answers0