#How to use serde to turn an integer into an enum?

2 messages · Page 1 of 1 (latest)

normal estuary
#

I have some JSON being sent to me that's like this

message: string
messageType: 0 | 1 | 2 | 3

I'm trying to deserialize it automatically with the derive macros but it's not working. What am I missing?

#[derive(Serialize, Debug, Deserialize)]
enum MessageType {
    Output = 0,
    Info = 1,
    Warning = 2,
    Error = 3,
}

#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
struct Log {
    message: String,
    message_type: MessageType,
}

pub async fn logs(Json(body): Json<Value>) -> StatusCode {
    dbg!(&body);
    let log: Log = serde_json::from_value(body).unwrap();

    match log.message_type {
        MessageType::Output | MessageType::Info => {
            println!("{}", log.message);
        }
        MessageType::Warning => {
            println!("{}", style(log.message).yellow());
        }
        MessageType::Error => {
            println!("{}", style(log.message).red());
        }
    }

    StatusCode::OK
}
[src/api/logs.rs:22:5] &body = Object {
    "message": String("testb print"),
    "messageType": Number(0),
}
thread 'tokio-runtime-worker' panicked at src/api/logs.rs:23:49:
called `Result::unwrap()` on an `Err` value: Error("invalid type: integer `0`, expected string or map", line: 0, column: 0)
fluid tundra