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

Internally tagged enum with boolean tag #880

Closed
dtolnay opened this issue Apr 15, 2017 · 1 comment
Closed

Internally tagged enum with boolean tag #880

dtolnay opened this issue Apr 15, 2017 · 1 comment
Labels

Comments

@dtolnay
Copy link
Member

dtolnay commented Apr 15, 2017

From IRC:

<PascalBach-M> I'm trying to deserialize a JSON respons from a REST call. I had some success with it using serde. Now I was wondering if I could improve the error handling by directly deserializing the response to a Result type.
<PascalBach-M> What I mean is that the response can be either a QueryResult or a QueryError which is dindicated by a bool `error: true` or `error:false` in the JSON response. Now I was wondering if it is possible to directly serialize this to a Result<QueryResult, QueryError>?

@dtolnay
Copy link
Member Author

dtolnay commented Apr 15, 2017

#745 is tracking a better solution to non-string tags but here is one possible approach for now:

#[macro_use]
extern crate serde_derive;

extern crate serde;
extern crate serde_json;

use serde::de::{self, Deserialize, Deserializer};
use serde_json::{Map, Value};

#[derive(Debug)]
enum PascalBach {
    Ok(QueryResult),
    Err(QueryError),
}

#[derive(Deserialize, Debug)]
struct QueryResult {
    path: String,
}

#[derive(Deserialize, Debug)]
struct QueryError {
    code: u16,
}

impl<'de> Deserialize<'de> for PascalBach {
    fn deserialize<D>(deserializer: D) -> Result<PascalBach, D::Error>
        where D: Deserializer<'de>
    {
        let mut map = Map::deserialize(deserializer)?;

        let error = map.remove("error")
            .ok_or_else(|| de::Error::missing_field("error"))
            .map(Deserialize::deserialize)?
            .map_err(de::Error::custom)?;
        let rest = Value::Object(map);

        if error {
            QueryError::deserialize(rest)
                .map(PascalBach::Err)
                .map_err(de::Error::custom)
        } else {
            QueryResult::deserialize(rest)
                .map(PascalBach::Ok)
                .map_err(de::Error::custom)
        }
    }
}

fn main() {
    let j = r#" {"error": false, "path": "/index.cgi" } "#;
    println!("{:?}", serde_json::from_str::<PascalBach>(j).unwrap());

    let j = r#" {"error": true, "code": 404 } "#;
    println!("{:?}", serde_json::from_str::<PascalBach>(j).unwrap());

    let j = r#" {} "#;
    println!("{}", serde_json::from_str::<PascalBach>(j).unwrap_err());
}

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

1 participant