0

I don't really know how to explain what I want to do, so I'll just make an example :

case class C1(id: String, name: String, description: String)
case class C2(id: String, status: Boolean)

trait Test[AnyRef] {

  implicit val writesC1 = Json.writes[C1]
  implicit val writesC2 = Json.writes[C2]

  def test(obj:AnyRef) = {
    println(Json.toJson(obj))
  }
}

object OC1 extends Test[C1] {}

object OC2 extends Test[C2] {}

val x = C1(1, "test", "desc test")

C1.test(x) // Here I want my C1 instance to be parsed as Json
4

1 回答 1

2

这个怎么样:

trait Test[T] {

  implicit val writesT = Json.writes[T]

  def test(obj: T) {
    println(Json.toJson(obj))
  }
}

object C1 extends Test[C1]

val x = C1(1, "test", "desc test")

OC1.test(x)

不幸的是,我现在没有安装游戏,我无法测试。

更新如果上部不起作用,这将:

trait Test[T] {
  implicit val writesT: Writes[T]
  // ...
}

object OC1 extends Test[C1] {
  implicit val writesT = Json.writes[C1]
}

但需要更多的打字。

于 2013-07-03T16:43:10.263 回答