0
votes

I tried to extract map data from json.

def getMap[K, V](js: JsValue, key: String): Map[K, V] = {
        js \ key match {
            case JsDefined(v) => v.as[Map[K, V]] // error here
            case _: JsUndefined => throw new Exception("Error")
        }
    }

No Json deserializer found for type Map[K,V]. Try to implement an implicit Reads or Format for this type. not enough arguments for method as: (implicit fjs: play.api.libs.json.Reads[Map[K,V]])Map[K,V]. Unspecified value parameter fjs.

This function works when I define specific type for Map (ex: v.as[ Map[String, Int]], but not in generic. How should I do with it?

1

1 Answers

1
votes

At some point you will have to have a specific K and V. At that point you will need the implicit readers in (implicit) scope, until then, you can just implicitly pass them:

def getMap[K, V](js: JsValue, key: String)(implicit reads: Reads[Map[K,V]]): Map[K, V] = {
        js \ key match {
            case JsDefined(v) => v.as[Map[K, V]] // error here
            case _: JsUndefined => throw new Exception("Error")
        }
    }

I am not sure why you would set it up this way though. Why not do either

(js \ key).as[Map[K,V]] if you want it to throw an error or (js \ key).asOpt[Map[K,V]] if an Option is ok as well. Or, also possible (js \ key).validate[Map[K,V]]