具有隐式json格式的Scala activerecord

时间:2015-02-25 09:30:16

标签: json scala activerecord implicit

我有一个scala-activerecord:

case class Person(name: String) extends ActiveRecord with Timestamps
object Person extends ActiveRecordCompanion[Person]

一切正常。

突然间,我想提供一个API并使用json表示实体,因此我修改了代码:

case class Person(name: String) extends ActiveRecord with Timestamps
object Person extends ActiveRecordCompanion[Person] with DefaultJsonProtocol {
  implicit val jsonFormat = jsonFormat1(Request)
}

现在它会导致异常:

com.github.aselab.activerecord.SchemaSettingException: Cannot find table definition of class Person
  at com.github.aselab.activerecord.ActiveRecordException$.tableNotFound(ActiveRecordException.scala:48)
  at com.github.aselab.activerecord.Config$$anonfun$schema$1.apply(ActiveRecordConfig.scala:29)
  at com.github.aselab.activerecord.Config$$anonfun$schema$1.apply(ActiveRecordConfig.scala:29)
  at scala.collection.MapLike$class.getOrElse(MapLike.scala:128)
  at scala.collection.AbstractMap.getOrElse(Map.scala:59)
  at com.github.aselab.activerecord.Config$.schema(ActiveRecordConfig.scala:29)
  at com.github.aselab.activerecord.ActiveRecordBaseCompanion$class.schema(ActiveRecord.scala:116)
  at Person$.schema$lzycompute(Request.scala:12)
  at Person$.schema(Request.scala:12)
  at com.github.aselab.activerecord.ActiveRecordBaseCompanion$class.table(ActiveRecord.scala:123)
  at Person$.table$lzycompute(Request.scala:12)
  at Person$.table(Request.scala:12)
  at com.github.aselab.activerecord.ActiveRecordBaseCompanion$class.all(ActiveRecord.scala:133)
  at Person$.all(Request.scala:12)
  at com.github.aselab.activerecord.inner.CompanionIterable$class.companionToIterable(Implicits.scala:15)
  at Person$.companionToIterable(Request.scala:12)
  at Person$.<init>(Request.scala:13)
  at Person$.<clinit>(Request.scala)
  ... 34 more

编辑: 我在ActiveRecordConfig.scala中添加了两个断点:

断点A在这里:

def schema(companion: ActiveRecordBaseCompanion[_, _]): ActiveRecordTables = {
  val clazz = companion.classInfo.clazz
  tables.getOrElse(clazz, throw ActiveRecordException.tableNotFound(clazz.toString))
}

断点B在这里:

def registerSchema(s: ActiveRecordTables) = {
  conf = s.config
  s.all.foreach(t => _tables.update(t.posoMetaData.clasz, s))
}

使用第一个代码(没有json隐式)执行命中断点B。

使用第二个代码(包括json隐式)执行首先命中断点A,导致异常。

1 个答案:

答案 0 :(得分:0)

Json支持scala-activerecord版本0.3.1中的工作,请参阅wikithis issue。至于现在,使用最新版本0.3.0,您可以使用第一个代码和表单值反序列化:

case class Person(name: String) extends ActiveRecord with Timestamps
object Person extends ActiveRecordCompanion[Person]

在你的...喷雾控制器:

import spray.httpx.SprayJsonSupport._
import spray.json.DefaultJsonProtocol._

requestContext.complete(Person.find(id).toFormValues)

方法toFormValues将返回Map[String, String],可以通过spray-json隐式转换为json。