Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deserialize Value into enum based on member variable #636

Closed
kyrias opened this issue Dec 1, 2016 · 3 comments
Closed

Deserialize Value into enum based on member variable #636

kyrias opened this issue Dec 1, 2016 · 3 comments
Labels

Comments

@kyrias
Copy link

kyrias commented Dec 1, 2016

Not sure if it's possible to do this in a nice way, but would be awesome if there was a way that didn't require manual deserialization. So, I'm trying to parse Matrix API responses, and one part of the JSON response has a content object that can look like this:

"content": {
    "body": "random text",
    "msgtype":"m.text"
}

But the actual fields in the object varies based on the msgtype field, so I want to have an enum with named fields and then deserialize into cases of this enum. Is it possible to do this in a nice way with serde?

@dtolnay
Copy link
Member

dtolnay commented Dec 1, 2016

We don't have something for this currently, but it would be a good candidate for a helper library. The other pattern that people commonly ask about is:

{
    "msgtype": "m.text",
    "content": {
        "body": "random text"
    }
}

#415 has a solution to that which you may be able to adapt to your case.

@kyrias
Copy link
Author

kyrias commented Dec 1, 2016

Cool, I'll see if I can use that, thanks.

@dtolnay
Copy link
Member

dtolnay commented Mar 6, 2017

@kyrias as of Serde 0.9 this would be done with an internally tagged enum.

#[derive(Serialize, Deserialize)]
#[serde(tag = "msgtype")]
enum Kyrias {
    #[serde(rename = "m.text")]
    Text { body: String }

    /* other variants */
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Development

No branches or pull requests

2 participants