Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/scala/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
scala-将json json值转换为泛型类型_Scala - Fatal编程技术网

scala-将json json值转换为泛型类型

scala-将json json值转换为泛型类型,scala,Scala,我试图从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") } } 未

我试图从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")
        }
    }
未找到类型映射[K,V]的Json反序列化程序。尝试实施 此类型的隐式读取或格式化。没有足够的论据支持 方法为:隐式fjs:play.api.libs.json.Reads[Map[K,V]]Map[K,V]。 未指定值参数fjs


当我为Map ex:v.as[Map[String,Int]]定义特定类型时,此函数起作用,但不是在泛型中。我应该如何处理它?

在某个时候,您必须有一个特定的K和V。在这一点上,您将需要隐式作用域中的隐式读取器,在此之前,您可以隐式传递它们:

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")
        }
    }
我不知道你为什么要这样设置。为什么不这样做呢

js\key.as[Map[K,V]] 如果你想让它抛出一个错误或者 js\key.asOpt[Map[K,V]] 如果一个选项也可以。或者,也有可能
js\key.validate[Map[K,V]]

谢谢,你救了我: