反序列化特征时的运行时错误

时间:2015-11-27 19:22:47

标签: scala spray

给出一个密封的特征,以及2个子类:

criteriaNumberMatches

我尝试定义一个import spray.json._ sealed trait HasColor { val hasColor: Boolean = true } sealed trait Ball { val name: String val age: Int } case class GreenBall(name: String, age: Int) extends Ball with HasColor case class SimpleBall(name: String, age: Int) extends Ball object GreenBall { import spray.json.DefaultJsonProtocol._ implicit val format: RootJsonFormat[GreenBall] = jsonFormat2(GreenBall.apply) } object SimpleBall { import spray.json.DefaultJsonProtocol._ implicit val format: RootJsonFormat[SimpleBall] = jsonFormat2(SimpleBall.apply) } 来定义如何(de)序列化JSON - > BallFormat,反之亦然。对于这个问题,我不关心如何实现Ball方法。

write

此代码编译,但尝试使用它会显示运行时错误:

object Ball {

    implicit object BallFormat extends RootJsonFormat[Ball] {

        override def write(ball: Ball): JsValue = 
            ???

        override def read(json: JsValue): Ball = json match {
            case JsObject(fields) =>
                fields.get("hasColor") match {
                    case None    => json.convertTo[SimpleBall]
                    case Some(_) => json.convertTo[GreenBall]
                }
        }
    }
}

这个运行时错误的原因是什么?

1 个答案:

答案 0 :(得分:2)

jsonformat提供的DefaultJsonProtocol方法不支持通过特征混合添加的字段。这意味着您必须为RootJsonFormat课程写一个完整的GreenBall,而不是使用jsonFormat

至少有一个构建在spray-json之上的库,它具有对序列化密封特征层次结构的开箱即用支持。看看spray-json-shapeless

相关问题