将JSON根对象读取器作为数组或对象进行喷射

时间:2015-12-18 07:48:59

标签: json scala deserialization spray-json

我有域模型:

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

谢谢!

1 个答案:

答案 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??
    }
  }