Json Parse obj没有case class ref

时间:2013-07-03 16:21:46

标签: json scala serialization playframework-2.0 deserialization

我真的不知道如何解释我想做什么,所以我只想举个例子:

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

1 个答案:

答案 0 :(得分: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]
}

但需要更多打字。