当我在 REPL 中执行时,它可以工作(由于mapWrites
范围内的隐含):
scala> Map("a"->1l, "b"->2l)
res0: scala.collection.immutable.Map[String,Long] = Map(a -> 1, b -> 2)
scala> Map("c" -> res0, "d" -> res0)
res1: scala.collection.immutable.Map[String,scala.collection.immutable.Map[String,Long]] = Map(c -> Map(a -> 1, b -> 2), d -> Map(a -> 1, b -> 2))
scala> import play.api.libs.json._
import play.api.libs.json._
scala> Json.toJson(res1)
res2: play.api.libs.json.JsValue = {"c":{"a":1,"b":2},"d":{"a":1,"b":2}}
为什么我的代码仍然无法编译(它与 REPL 中的类型相同)?
No Json deserializer found for type Map[String,Map[String,Long]]. Try to implement an implicit Writes or Format for this type.
[编辑] 我找到了一种解决方法,但我不明白我为什么需要它:
implicit def mapWrites = Writes[Map[String,Map[String,Long]]] ( m => Writes.mapWrites(Writes.mapWrites[Long]).writes(m))