title: Decoding into recursive ADTs with argonaut
body: <p>I'm trying to parse json like</p>
  
  <pre><code>{
    "element": "string",
    "content": "application/json"
  }
  </code></pre>
  
  <p>where <code>element</code> decides which type the json is. But my code fails to parse.</p>
  
  <p><a href="http://scastie.org/15213" rel="nofollow">http://scastie.org/15213</a></p>
  
  <pre><code>import scalaz._, Scalaz._
  import argonaut._, Argonaut._, Shapeless._
  
  case class ArrayAttributes(default: List[StringElement])
  
  sealed trait Element
  case class StringElement(content: String) extends Element
  case class ArrayElement(attributes: ArrayAttributes, content: List[Element]) extends Element
  case class Reference(element: String) extends Element { def content = element }
  
  object Parser {
  
    def kindDecode[T](
      kinds: Map[String, DecodeJson[T]],
      fail: HCursor =&gt; DecodeResult[T] = { c: HCursor =&gt; DecodeResult.fail[T]("expected one of ${kind.keys}", c.history) }): DecodeJson[T] = DecodeJson(c =&gt;
      (c --\ "element").as[String].flatMap { kind =&gt;
        kinds.get(kind).map(_.decode(c)).getOrElse(fail(c))
      }
    )
  
    implicit def elementDecode: DecodeJson[Element] = kindDecode(
      Map(
        "string" -&gt; DecodeJson.of[StringElement].map(identity[Element]),
        "array" -&gt; arrayDecode.map(identity[Element])
      ),
      { c =&gt; DecodeJson.of[Reference].decode(c).map(identity[Element]) }
    )
  
    def arrayDecode: DecodeJson[ArrayElement] = jdecode2L(ArrayElement.apply)("attributes", "content")
  
  }
  </code></pre>