How can I deserialize an enum when the case doesn't match?

ぐ巨炮叔叔 提交于 2020-06-08 19:20:25

问题


I have a JSON structure that looks like this:

{ "type": "suite", "event": "started", "test_count": 1 }

I want to deserialize into these structs:

#[derive(Debug, Deserialize)]
enum ResultType {
    Suite,
    Test,
}

#[derive(Debug, Deserialize)]
enum ResultEvent {
    Started,
    Failed,
    Ok,
}

#[derive(Debug, Deserialize)]
struct JsonResult {
    #[serde(rename(deserialize = "type"))]
    test_type: ResultType,
    event: ResultEvent,
    test_count: Option<u32>,
}

I can't find a way to make serde_json use the correct case. I keep getting these errors:

Error("unknown variant `suite`, expected `Suite` or `Test`", line: 1, column: 17)

If I change the case of the enum values to all lowercase or all uppercase it works, but I'd like to be able to use PascalCase.


回答1:


You just need to put #[serde(rename_all = "snake_case")] before the enum definition.



来源:https://stackoverflow.com/questions/59167416/how-can-i-deserialize-an-enum-when-the-case-doesnt-match

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!