我正在尝试解析json
{
"element": "string",
"content": "application/json"
}
whereelement
决定 json 的类型。但是我的代码无法解析。
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 => DecodeResult[T] = { c: HCursor => DecodeResult.fail[T]("expected one of ${kind.keys}", c.history) }): DecodeJson[T] = DecodeJson(c =>
(c --\ "element").as[String].flatMap { kind =>
kinds.get(kind).map(_.decode(c)).getOrElse(fail(c))
}
)
implicit def elementDecode: DecodeJson[Element] = kindDecode(
Map(
"string" -> DecodeJson.of[StringElement].map(identity[Element]),
"array" -> arrayDecode.map(identity[Element])
),
{ c => DecodeJson.of[Reference].decode(c).map(identity[Element]) }
)
def arrayDecode: DecodeJson[ArrayElement] = jdecode2L(ArrayElement.apply)("attributes", "content")
}