Skip to content
This repository was archived by the owner on Jan 29, 2023. It is now read-only.

How can I deserialize an enum in struct? #51

Open
yancheng199287 opened this issue May 26, 2021 · 1 comment
Open

How can I deserialize an enum in struct? #51

yancheng199287 opened this issue May 26, 2021 · 1 comment

Comments

@yancheng199287
Copy link

yancheng199287 commented May 26, 2021


#[derive(Debug,Deserialize)]
enum RoleType {
    Admin,
    User,
    VipUser,
}

#[derive(Debug, Deserialize)]
struct User {
    name: String,
    age: u8,
    weight: u8,
    high: f32,
 #[serde(flatten)]
    role_type:RoleType
}


#[test]
fn test01() {
    let s = r#"{
        name="yancheng"
        age=28
        weight=76
        high=1.77
        role_type="VipUser"
    }"#;

    let user: User = hocon::de::from_str(s).unwrap();

    println!("{:?}", user)
}
called `Result::unwrap()` on an `Err` value: Deserialization { message: ".: no variant of enum RoleType found in flattened data" }
thread 'test01' panicked at 'called `Result::unwrap()` on an `Err` value: Deserialization { message: ".: no variant of enum RoleType found in flattened data" }', examples\hocon_test01.rs:50:45
stack backtrace:


@mockersf
Copy link
Owner

#[derive(Debug, Deserialize)]
struct User {
    name: String,
    age: u8,
    weight: u8,
    high: f32,
 #[serde(flatten)]
    role_type:RoleType
}

You can't flatten a unit enum like RoleType.

This struct is working:

#[derive(Debug, Deserialize)]
struct User {
    name: String,
    age: u8,
    weight: u8,
    high: f32,
    role_type: RoleType,
}

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants