如果我有一个特点,如:
trait MyTrait[T] {
def myVal: T
}
然后我有一个案例类,如:
case class MyClass(val foo: Int, val myVal: Boolean) extends MyTrait[Boolean]
最后,我有另一个案例类
case class MyOtherClass(val bar: MyTrait[_])
如何将最后一个类序列化和反序列化为Json?
我对myClass进行了如下读写:
object MyClass {
implicit def MyClassWrites(implicit fmt: MyClass): Writes[MyClass] = new Writes[MyClass] {
override def writes(m: MyClass) = Json.obj(
"foo" -> m.foo,
"myVal" -> m.myVal // myVal should be Boolean
)
}
implicit def MyClassReads(implicit fmt: Reads[MyClass]): Reads[MyClass] = new Reads[MyClass] {
override def reads(json: JsValue): MyClass = new MyClass(
(json \ "foo").as[Int],
true
)
}
}
myOtherClass还具有读写功能,如下所示:
object MyOtherClass {
implicit def MyOtherClassWrites(implicit fmt: MyOtherClass): Writes[MyOtherClass] = new Writes[MyOtherClass] {
override def writes(m: MyOtherClass) = Json.obj(
"bar" -> Json.toJson(m.bar)
)
}
implicit def MyOtherClassReads(implicit fmt: Reads[MyOtherClass]): Reads[MyOtherClass] = new Reads[MyOtherClass] {
override def reads(json: JsValue): MyClass = new MyOtherClass(
(json \ "bar").as[MyClass[Boolean]]
)
}
}
编译时,我收到以下错误:
Error:(43, 28) No Json serializer found for type A$A135.this.MyTrait[_$1]. Try to implement an implicit Writes or Format for this type.
"bar" -> Json.toJson(m.bar)
^
如果我按如下方式将特写添加到特征:
object MyTrait {
implicit def MyClassWrites(implicit fmt: MyTrait[_]): Writes[MyTrait[_]] = new Writes[MyTrait[_]] {
override def writes(m: MyTrait[_]) = Json.obj(
"myVal" -> Json.toJson(m.myVal) // myVal should be Boolean
)
}
implicit def MyClassReads(implicit fmt: Reads[MyTrait[_]]): Reads[MyTrait[_]] = new Reads[MyTrait[_]] {
override def reads(json: JsValue): MyTrait[_] = new MyClass(2, false)
}
}
我现在收到此错误:
Error:(10, 30) No Json serializer found for type _$4. Try to implement an implicit Writes or Format for this type.
"myVal" -> Json.toJson(m.myVal) // myVal should be Boolean
^
我迷失在这里,是不是有办法将bar序列化为好像是MyClass?
我还试图将MyTrait的编剧改为:
override def writes(m: MyTrait[_]) = {
m match {
case c: MyClass => Json.toJson(c)
}
}
现在编写特征的编写者,但我们回到第一个错误:
Error:(45, 28) No Json serializer found for type A$A199.this.MyTrait[_$9]. Try to implement an implicit Writes or Format for this type.
"bar" -> Json.toJson(m.bar)
^
我没有得到它,我已经定义了作家和读者,我没有??
提前致谢。
答案 0 :(得分:0)
尝试定义以下实例。
implicit def MyTRead[T](implicit r: Reads[T]): Reads[MyTrait[T]] = ???
implicit def MyTWrite[T](implicit r: Writes[T]): Writes[MyTrait[T]] = ???