简体   繁体   中英

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"}}

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 .

struct FooRes {
   result:RESULT,
}

How do I do this?

Thunks, I solved

https://serde.rs/enum-number.html

Correct #[derive(Serialize_repr, Deserialize_repr, PartialEq, Debug)] Not #[derive(Debug, Serialize, Deserialize)]

On Enum , tnx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM