Skip to content

Add pop method to json Decoder #17377

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

Closed
yaitskov opened this issue Sep 18, 2014 · 2 comments
Closed

Add pop method to json Decoder #17377

yaitskov opened this issue Sep 18, 2014 · 2 comments

Comments

@yaitskov
Copy link

Now it's impossible to implement Decodable for a map with different value types
because read_* methods lose the stack head anyway.
Decodable doesn't have a method returning the stack head as-is without any type casting.

Let's look a case where Json dictionary has values with int and String types.

extern crate serialize;
use serialize::{Decodable, Decoder};
use serialize::json::{Json, Boolean, String, Null, I64, U64, F64};
use serialize::json;

#[deriving(Show)]
struct Primitive(Json);

impl<S: Decoder<E>, E> Decodable<S, E> for Primitive {
    fn decode(decoder: &mut S) -> Result<Primitive, E> {
        match decoder.pop() {      
            n @ I64(_)    => Primitive(n),
            n @ U64(_)    => Primitive(n),
            n @ F64(_)    => Primitive(n),
            s @ String(_) => Primitive(s),
            bad           => fail!("bad {}", bad)
       }
    }
}
@gwicke
Copy link

gwicke commented Nov 18, 2014

It would be even nicer to get automatic handling for type alternatives through a derived Decodable implementation for an enum. That could potentially cover the majority of cases for JSON without a need to write custom decoders.

There is also some related discussion at http://stackoverflow.com/questions/25604339/parse-json-value-as-enum-in-rust.

@steveklabnik
Copy link
Member

As this library is out of tree, I'm moving this issue to that repo: rust-lang-deprecated/rustc-serialize#44 Thanks!

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

No branches or pull requests

3 participants