title: serde: deserialize a field based on the value of another field
body: <p>I would like to deserialize a wire format, like this JSON, into the <code>Data</code> structure below and I am failing to write the serde <code>Deserialize</code> implementations for the corresponding rust types.</p>
  <pre class="lang-json prettyprint-override"><code>{ &quot;type&quot;: &quot;TypeA&quot;, &quot;value&quot;: { &quot;id&quot;: &quot;blah&quot;, &quot;content&quot;: &quot;0xa1b..&quot; } }
  </code></pre>
  <pre class="lang-rust prettyprint-override"><code>enum Content {
     TypeA(Vec&lt;u8&gt;),
     TypeB(BigInt), 
  }
  
  struct Value {
      id: String,
      content: Content,
  }
  
  struct Data {
     typ: String,
     value: Value,
  }
  </code></pre>
  <p>The difficulty is selecting the correct value of the <code>Content</code> enumeration, which is based on the <code>typ</code> value.
  As far as I know, deserialization in serde is stateless, an hence there is no way of either</p>
  <ul>
  <li>knowing what the value of <code>typ</code> is at the time of deserialization of <code>content</code> (even though the deserialization order is guaranteed)</li>
  <li>or injecting the value of <code>typ</code> in the deserializer then collecting it.</li>
  </ul>
  <p>How can this be achieved with serde ?</p>
  <p>I have looked at</p>
  <ul>
  <li><a href="https://docs.rs/serde_state/0.4.8/serde_state/index.html" rel="noreferrer">serde_state</a> but I cannot get the macros working and this library is wrapping serde, which worries me</li>
  <li><a href="https://docs.serde.rs/serde/de/trait.DeserializeSeed.html" rel="noreferrer">DeserializeSeed</a> but my undestanding is that it must be used in place of <code>Deserialize</code> for <em>all</em> types and my data model is big</li>
  </ul>
  <p>The existing SO answers usually exploit the fact that the related fields are at the same level. This is not the case here: the actual data model is big, deep and the fields are &quot;far apart&quot;</p>