我有域模型:
sealed trait MyTrait
case class MyObject(a: String) extends MyTrait
case class MyArray(a: Seq(MyObject)) extends MyTrait
示例用法如下:
// array
[{"a": "foo"}, {"a": "bar"}]
//object
{"a": "foobar"}
我想为MyTrait编写一个Spray JSON阅读器,如:
implicit val myTraitReader: RooJsonReader[MyTrait] = new RootJsonReader[MyTrait] {
override def read(json: JsValue): MyTrait = {
// MAGIC?
// I need to be able to distinguish between JsObject and JsArray
// If I do json.asJsObject this is a JsObject then :D
// there is not json.asJsArray?
// How to pattern match on this use case?
}
}
所有问题都被注释掉了。 :d
谢谢!
答案 0 :(得分:0)
下面的内容怎么样?
implicit val myTraitReader: RootJsonReader[MyTrait] = new RootJsonReader[MyTrait] {
import MyObjectProtocol._
import MyArrayProtocol._
override def read(json: JsValue): MyTrait = json match {
case jsObj: JsObject => ??? // Convert to MyObject here
case jsArr: JsArray => ??? // Convert to MyArray here
case _ => ??? // A JsNull here??
}
}