<p dir="auto">Let's say that you have a JSON document similar to this:</p>
<div class="highlight highlight-source-json notranslate position-relative overflow-auto" dir="auto" data-snippet-clipboard-copy-content="{
    &quot;value&quot;: 5,
}"><pre class="notranslate">{
    <span class="pl-ent">"value"</span>: <span class="pl-c1">5</span>,
}</pre></div>
<p dir="auto">And the value of <code class="notranslate">value</code> can be either a number or a string.</p>
<p dir="auto">There is currently no way to write a generic implementation of <code class="notranslate">Decodable</code> that can handle this. Attempting to read the value of <code class="notranslate">value</code> will remove it and throw it away, even if the read triggers an error. You can't try to read a number and then read a string if it fails.</p>
<p dir="auto">The element is returned in the <code class="notranslate">DecoderError</code>, so it should be possible to write an implementation of <code class="notranslate">Decodable</code> specifically for Json, but if you do so you can't put the object within another object that has <code class="notranslate">#[deriving(Decodable)]</code>.</p>
<p dir="auto">Now it's impossible to implement Decodable for a map with different value types<br>
because read_* methods lose the stack head anyway.<br>
Decodable doesn't have a method returning the stack head as-is without any type casting.</p>
<p dir="auto">Let's look a case where Json dictionary has values with int and  String types.</p>
<div class="snippet-clipboard-content notranslate position-relative overflow-auto" data-snippet-clipboard-copy-content="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&lt;S: Decoder&lt;E&gt;, E&gt; Decodable&lt;S, E&gt; for Primitive {
    fn decode(decoder: &amp;mut S) -&gt; Result&lt;Primitive, E&gt; {
        match decoder.pop() {      
            n @ I64(_)    =&gt; Primitive(n),
            n @ U64(_)    =&gt; Primitive(n),
            n @ F64(_)    =&gt; Primitive(n),
            s @ String(_) =&gt; Primitive(s),
            bad           =&gt; fail!(&quot;bad {}&quot;, bad)
       }
    }
}"><pre class="notranslate"><code class="notranslate">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&lt;S: Decoder&lt;E&gt;, E&gt; Decodable&lt;S, E&gt; for Primitive {
    fn decode(decoder: &amp;mut S) -&gt; Result&lt;Primitive, E&gt; {
        match decoder.pop() {      
            n @ I64(_)    =&gt; Primitive(n),
            n @ U64(_)    =&gt; Primitive(n),
            n @ F64(_)    =&gt; Primitive(n),
            s @ String(_) =&gt; Primitive(s),
            bad           =&gt; fail!("bad {}", bad)
       }
    }
}
</code></pre></div>