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, Object]</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> <p>Jackson doesn't know how to deserialize the Scala collection class <code>scala.collection.immutable.Map</code>, because it doesn't implement any of the Java collection interfaces.</p> <p>You can either deserialize to a Java collection:</p> <pre><code>val mapData = mapper.readValue(jsonContent, classOf[java.util.Map[String,String]]) </code></pre> <p>or add the Scala module to the mapper:</p> <pre><code>mapper.registerModule(DefaultScalaModule) val mapData = mapper.readValue(jsonContent, classOf[Map[String,String]]) </code></pre> <p>or <strong>you can also try like this</strong> </p> <pre><code>import play.api.libs.json._ val a1=Map("val1"-&gt;"a", "val2"-&gt;"b") Json.toJSon(a1) </code></pre> <p>Because a1 is just <code>Map[String,String]</code> that works OK.</p> <p>But if I have something more complex like where I have <code>Map[String,Object]</code>, that doesn't work:</p> <pre><code> val a = Map("val1" -&gt; "xxx", "val2"-&gt; List("a", "b", "c")) Json.toJSon(a1) &gt;&gt;&gt; error: No Json deserializer found for type scala.collection.immutable.Map[String,Object] </code></pre> <p>I found that I can do something like the following:</p> <pre><code>val a2 = Map("val1" -&gt; Json.toJson("a"), "val2" -&gt; Json.toJson(List("a", "b", "c"))) Json.toJson(a2) </code></pre> <p>And that works.`</p>
 

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