score:1

Accepted answer

With colleague we have prepared a generic class that provides JSON serialization for Map[E <: Enum[E], T] type.

The Enum type is always converted to String as it is required for JsObject key. The other parameter is generic and is converted using the implicit format: Format[T]

import play.api.data.validation.ValidationError
import play.api.libs.json._    
import scala.util.{Failure, Success, Try}

class MapEnumFormat[E <: Enum[E], T](valueOf: (String => E))(implicit format: Format[T]) extends Format[Map[E, T]] {

  override def writes(o: Map[E, T]): JsValue = {
    JsObject(o.map { case (a, b) => (a.name, Json.toJson(b)) })
  }

  override def reads(json: JsValue): JsResult[Map[E, T]] = {
    val result = Try(json.as[Map[String, T]].map {
      case (key, value) =>
        valueOf(key) -> value
    })

    result match {
      case Success(status) =>
        JsSuccess(status)
      case Failure(th) =>
        JsError(ValidationError(s"Error while serializing $json: $th"))
    }
  }

}

score:3

Note that it is mandatory for Json keys to be strings.

Following code works

Json.toJson(Map("mon" -> EnumA.MON))

Following code does not work because key for valid Json should always be string. Here the key is EnumA.Value which is not String.

scala> Json.toJson(Map(EnumA.MON -> "mon"))
    <console>:19: error: No Json serializer found for type scala.collection.immutable.Map[EnumA.Value,String]. Try to implement an implicit Writes or Format for this type.
           Json.toJson(Map(EnumA.MON -> "mon"))

But if you want it work as expected provide a writes

 implicit val writes = new Writes[Map[EnumA.Value, String]] {
      override def writes(o: Map[EnumA.Value, String]): JsValue = Json.toJson(o.map { case (a, b) => Json.parse(s"""{${Json.toJson(a)}:${Json.toJson(b)}}""")}.toList)
    }

now following code works

 Json.toJson(Map(EnumA.MON -> "hello"))

You can declare format for EnumA as following

  object EnumA extends Enumeration {
    val MON = Value("monday")
    val TUE = Value("Tuesday")

    implicit val format = new Format[EnumA.Value] {
      override def writes(o: EnumA.Value): JsValue = Json.toJson(o.toString)
      override def reads(json: JsValue): JsResult[EnumA.Value] = json.validate[String].map(EnumA.withName(_))
    }
  }

Scala REPL output

scala>       object EnumA extends Enumeration {
     |         val MON = Value("monday")
     |         val TUE = Value("Tuesday")
     |
     |         implicit val format = new Format[EnumA.Value] {
     |           override def writes(o: EnumA.Value): JsValue = Json.toJson(o.toString)
     |           override def reads(json: JsValue): JsResult[EnumA.Value] = json.validate[String].map(EnumA.withName(_))
     |         }
     |       }
defined object EnumA

scala> Json.toJson(EnumA.MON)
res0: play.api.libs.json.JsValue = "monday"

scala> (Json.parse("""{"a": "monday"}""") \ "a").validate[EnumA.Value]
res7: play.api.libs.json.JsResult[EnumA.Value] = JsSuccess(monday,)

scala> (Json.parse("""{"a": "monday"}""") \ "a").validate[EnumA.Value].get
res10: EnumA.Value = monday

scala> Json.toJson(Map("mon" -> EnumA.MON))
res2: play.api.libs.json.JsValue = {"mon":"monday"}

scala> Json.toJson(Map(EnumA.MON -> "mon"))
<console>:19: error: No Json serializer found for type scala.collection.immutable.Map[EnumA.Value,String]. Try to implement an implicit Writes or Format for this type.
       Json.toJson(Map(EnumA.MON -> "mon"))

scala> implicit val writes = new Writes[Map[EnumA.Value, String]] {
     |       override def writes(o: Map[EnumA.Value, String]): JsValue = Json.toJson(o.map { case (a, b) => Json.parse(s"""{${Json.toJson(a)}:${Json.toJson(b)}}""")}.toList)
     |     }
writes: play.api.libs.json.Writes[Map[EnumA.Value,String]] = $anon$1@65aebb67

scala>  Json.toJson(Map(EnumA.MON -> "hello"))
res2: play.api.libs.json.JsValue = [{"monday":"hello"}]

Related Query

More Query from same tag