本文介绍了如果大小写不匹配,如何反序列化枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的JSON结构:
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>,
}
我找不到使serde_json使用正确大小写的方法.我不断收到这些错误:
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)
如果我将枚举值的大小写更改为全部小写或全部大写,则可以,但是我希望能够使用PascalCase.
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.
推荐答案
您只需将 c1> 在枚举定义之前.
You just need to put #[serde(rename_all = "snake_case")]
before the enum definition.
这篇关于如果大小写不匹配,如何反序列化枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!