Skip to content
This repository has been archived by the owner on Dec 1, 2023. It is now read-only.

Add pop method to json Decoder #44

Closed
steveklabnik opened this issue Jan 29, 2015 · 2 comments
Closed

Add pop method to json Decoder #44

steveklabnik opened this issue Jan 29, 2015 · 2 comments

Comments

@steveklabnik
Copy link
Contributor

Issue by yaitskov
Thursday Sep 18, 2014 at 20:14 GMT

For earlier discussion, see rust-lang/rust#17377

This issue was labelled with: in the Rust repository


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)
       }
    }
}
@oli-obk
Copy link
Contributor

oli-obk commented Jan 29, 2015

Note: Decodable is not a generic trait. The decode function is generic instead.
Note2: You can derive the Decodable implementation for BTreeMap<String, Option<String>> or any other enum type that derives Decodable as Value.

Obviously Note2 does not work to decode arbitrary json formats, only those that also were encoded by a derived Encodable trait.

As the decoder could also be any other decoder (like a binary decoder), the type of the field to read might not be available. Implementing a generic pop is therefor not possible. Making the pop method from json::Decoder public and waiting for negative trait bounds might work (rust-lang/rfcs#586).

@alexcrichton
Copy link
Contributor

I'm going to close this now that this crate is deprecated in favor of serde. We're discontinuing feature development in rustc-serialize but will still continue to merge bug fixes if they arise.

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

3 participants