How do I serialize an enum to a number and deserialize from a number via serde-json?

862 views Asked by At
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?

1

There are 1 answers

0
Ryo-chan On

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