Reputation: 11741
I'm new to Play (and Scala). I'm trying to write a simple Play application that calls some Java code.
I want to convert a scala.collection.mutable.Map[String,Array[String]]
to a JSON String. But this clearly doens't work.
Based on this I'm assuming I've to implement Writes. My current code (which is clearly incorrect) looks like the following:
implicit val myWrites = new Writes[scala.collection.mutable.Map[String,Array[String]]] {
def writes(res: scala.collection.mutable.Map[String,Array[String]]) = {
val x = res.foreach { kv => Json.obj(
kv._1 -> ( kv._2.reduceLeft(_ + "," + _).mkString)
) }
Json.toJson(x)
}
}
Any pointers that will help me make progress would be appreciated.
Upvotes: 2
Views: 592
Reputation: 179119
You don't have to write any Writes
implementation. All you need to do is transform the mutable map into an immutable one, simply by calling the toMap
method:
scala> import play.api.libs.json._
import play.api.libs.json._
scala> import scala.collection.mutable
import scala.collection.mutable
scala> val im = Map("foo" -> Array("bar", "baz"))
im: scala.collection.immutable.Map[String,Array[String]] = Map(foo -> Array(bar, baz))
scala> Json.stringify(Json.toJson(im))
res8: String = {"foo":["bar","baz"]}
scala> val mm = mutable.Map("foo" -> Array("bar", "baz"))
mm: scala.collection.mutable.Map[String,Array[String]] = Map(foo -> Array(bar, baz))
scala> Json.stringify(Json.toJson(mm))
<console>:20: error: No Json deserializer found for type scala.collection.mutable.Map[String,Array[String]]. Try to implement an implicit Writes or Format for this type.
Json.stringify(Json.toJson(mm))
^
scala> Json.stringify(Json.toJson(mm.toMap))
res10: String = {"foo":["bar","baz"]}
Upvotes: 5