[英]How do I serialize an enum to a number and deserialize from a number via serde-json?
struct ResponseData<T> {
success : bool,
res_data : T,
}
struct FooRes {
result:RESULT,
}
num RESULT {
RESULT_OK = 0,
RESULT_NG = 1,
}
fn test(){
let s = ResponseData::<FooRes>{
success : true,
res_data : FooRes{
result:RESULT::RESULT_OK,
},
};
let st = serde_json::to_string(&s).unwrap();
println!("json={}",st);
json={"success":true,"resData":{"result":"RESULT_OK"}} json={"success":true,"resData":{"result":"RESULT_OK"}}
I need the outcome to be {"result":0}
, not {"result":"RESULT_OK"}
, when serializing the enum into a number value, and {"success":true,"resData":{"result":0}}
to deserialize to the enum member result
.我需要结果是
{"result":0}
,而不是{"result":"RESULT_OK"}
,当将枚举序列化为数值时, {"success":true,"resData":{"result":0}}
反序列化为枚举成员result
。
struct FooRes {
result:RESULT,
}
How do I do this?我该怎么做呢?
Thunks, I solved大佬,我解决了
https://serde.rs/enum-number.html https://serde.rs/enum-number.html
Correct #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] Not #[derive(Debug, Serialize, Deserialize)]正确 #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] 不 #[derive(Debug, Serialize, Deserialize)]
On Enum , tnx在枚举上,tnx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.