我有以下类型,我想序列化和反序列化!
val myType = Map[Long, MyType]
MyType是特质
trait MyType {
def x: String
def y: Int
}
然后我将MyType的一些实现作为:
case class A(
val x: String,
val y: Int)
extends MyType
case class B(
val x: String,
val y: Int)
extends MyType
我编写了以下JSON格式:
implicit val mapReads: Reads[Map[Long, MyType]] = new Reads[Map[Long, MyType]] {
def reads(jv: JsValue): JsResult[Map[Long, MyType]] =
JsSuccess(jv.as[Map[Long, MyType]].map{case (k, v) =>
k -> v.asInstanceOf[MyType]
})
}
implicit val mapWrites: Writes[Map[Long, MyType]] = new Writes[Map[Long, MyType]] {
def writes(map: Map[Long, MyType]): JsValue =
Json.obj(map.map{case (s, o) =>
val ret: (String, JsValueWrapper) = s.toString -> Json.toJson(o)
ret
}.toSeq:_*)
}
implicit val mapFormat: Format[Map[Long, MyType]] = Format(mapReads, mapWrites)
当我运行上面引用JSON格式化程序的测试时,我在此行的reads函数中出现StackOverflow错误:
JsSuccess(jv.as[Map[Long, MyType]].map{case (k, v) =>
我不清楚为什么会这样?有什么想法吗?