scalaplayframeworkplayframework-2.5play-json

Play Framework: No implicit format for Map


Using Play 2.5 I cannot seem to serialize a Map[SomeCaseClass, String]

case class SomeCaseClass(value: String)

implicit val formatSomeCaseClass = Json.format[SomeCaseClass]

Json.toJson(Map[SomeCaseClass, String](SomeCaseClass("") -> ""))

Errors with

No Json serializer found for type scala.collection.immutable.Map[SomeCaseClass,String]. Try to implement an implicit Writes or Format for this type.

Unless i'm missing something obvious, there is an implicit format for that type immediately above.

If I try something more simple like:

Json.toJson(Something(""))
Json.toJson(Map[String, String]("" -> ""))

It works fine. What am I missing when using a Map with a more complex type e.g. SomeCaseClass?


Solution

  • I think the problem here comes from json. Maps get converted to JSON objects which consist of key/value pairs. The keys in those objects must be strings.

    So a Map[String, T] can get converted to a json object but not an arbitrary Map[U, T].