我有这个播放框架 2 代码(简化):
import formatters.json.IdeaTypeFormatter._
object IdeaTypes extends Controller {
def list = Action { request =>
Ok(toJson(IdeaType.find(request.queryString)))
}
def show(id: Long) = Action {
IdeaType.findById(id).map { ideatype =>
Ok(toJson(ideatype))
}.getOrElse(JsonNotFound("Type of idea with id %s not found".format(id)))
}
}
IdeaType
类 extends Entity
,它的伴生对象IdeaType
, extends EntityCompanion
。
如您所料,我在每个控制器中都有这种代码,所以我想将基本行为提取到特征中,如下所示:
abstract class EntityController[A<:Entity] extends Controller {
val companion: EntityCompanion
val name = "entity"
def list = Action { request =>
Ok(toJson(companion.find(request.queryString)))
}
def show(id: Long) = Action {
companion.findById(id).map { entity =>
Ok(toJson(entity))
}.getOrElse(JsonNotFound("%s with id %s not found".format(name, id)))
}
}
但我收到以下错误:
[error] EntityController.scala:25: No Json deserializer found for type List[A].
[error] Try to implement an implicit Writes or Format for this type.
[error] Ok(toJson(companion.find(request.queryString)))
[error] ^
[error] EntityController.scala:34: No Json deserializer found for type A.
[error] Try to implement an implicit Writes or Format for this type.
[error] Ok(toJson(entity))
[error] ^
我不知道如何判断隐式Writes
将由实现EntityController
特征的类实现(或继承抽象类EntityController
)
- 编辑
到目前为止,我正在这样做:
abstract class CrudController[A <: Entity](
val model: EntityCompanion[A],
val name: String,
implicit val formatter: Format[A]
) extends Controller {
并像这样使用它
object CrudIdeaTypes extends CrudController[IdeaType](
model = IdeaType,
name = "type of idea",
formatter = JsonIdeaTypeFormatter
)
我无法让 scala 使用隐式自动选择它。我尝试使用此导入,但没有成功
import formatters.json.IdeaTypeFormatter._