How to read Map[String,Any]

This is my code:

case class MyData(id,Int,field:Map[String,Any])

object MyData {
  implicit val format:Format[MyData] = Json.format

And I got an error saying that no implicit found for Map[String,Any].

You would need to be able to provide a JSON format for Any, which doesn’t really make a lot of sense. Are you sure your map really needs to support any type of value? What’s actually in the JSON?

sir I want to insert a custom form .
“data”: {


so I need a case class Data(data:Map[String,Any])
value could be Int,String,Boolean

One option might be to use Map[String,JsValue] instead.

Otherwise, if you really want to use Map[String, Any], you can define your own reader for Any:

  case class Data(data:Map[String,Any])
  object Data {
    private implicit val readsAny: Reads[Any] = Reads {
      case JsString(s) => JsSuccess(s)
      case JsNumber(n) => JsSuccess(n)
      case JsBoolean(b) => JsSuccess(b)
      case jsValue => JsError(s"Unknown type: $jsValue")
    implicit val reads: Reads[Data] = Json.reads

If you also need to be able to generate JSON from these classes, then you would create a Writes[Any] that reverses the operation. However you would need to be careful not to add anything to the map that can’t be converted to JSON, or else you’ll get a runtime error.

1 Like