Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Play 2.1 JSON API does not provide a serializer for the Type <code>Map[String, Ojbect]</code>.</p> <p>Define <code>case class</code> and <code>Format</code> for the specific type instead of <code>Map[String, Object]</code>:</p> <pre><code>// { "val1" : "xxx", "val2" : ["a", "b", "c"] } case class Hoge(val1: String, val2: List[String]) implicit val hogeFormat = Json.format[Hoge] </code></pre> <p>If you don't want to create case class. The following code provides JSON serializer/deserializer for Map[String, Object]:</p> <pre><code>implicit val objectMapFormat = new Format[Map[String, Object]] { def writes(map: Map[String, Object]): JsValue = Json.obj( "val1" -&gt; map("val1").asInstanceOf[String], "val2" -&gt; map("val2").asInstanceOf[List[String]] ) def reads(jv: JsValue): JsResult[Map[String, Object]] = JsSuccess(Map("val1" -&gt; (jv \ "val1").as[String], "val2" -&gt; (jv \ "val2").as[List[String]])) } </code></pre> <hr> <h2>More dynamically</h2> <pre><code>import play.api.libs.json._ import play.api.libs.json.Reads._ import play.api.libs.json.Json.JsValueWrapper implicit val objectMapFormat = new Format[Map[String, Object]] { def writes(map: Map[String, Object]): JsValue = Json.obj(map.map{case (s, o) =&gt; val ret:(String, JsValueWrapper) = o match { case _:String =&gt; s -&gt; JsString(o.asInstanceOf[String]) case _ =&gt; s -&gt; JsArray(o.asInstanceOf[List[String]].map(JsString(_))) } ret }.toSeq:_*) def reads(jv: JsValue): JsResult[Map[String, Object]] = JsSuccess(jv.as[Map[String, JsValue]].map{case (k, v) =&gt; k -&gt; (v match { case s:JsString =&gt; s.as[String] case l =&gt; l.as[List[String]] }) }) } </code></pre> <p>Sample code:</p> <pre><code> val jv = Json.toJson(Map("val1" -&gt; "xxx", "val2" -&gt; List("a", "b", "c"), "val3" -&gt; "sss", "val4" -&gt; List("d", "e", "f"))) println(jv) val jr = Json.fromJson[Map[String, Object]](jv) println(jr.get) </code></pre> <p>The output:</p> <pre><code>&gt; {"val1":"xxx","val2":["a","b","c"],"val3":"sss","val4":["d","e","f"]} &gt; Map(val1 -&gt; xxx, val2 -&gt; List(a, b, c), val3 -&gt; sss, val4 -&gt; List(d, e, f)) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload