Scala json验证程序包含URI的字符串
我试图通过使用本文来实现验证 基本上,如果存在,我希望得到值,如果不存在,则返回nullScala json验证程序包含URI的字符串,json,scala,Json,Scala,我试图通过使用本文来实现验证 基本上,如果存在,我希望得到值,如果不存在,则返回null val nextPage: JsResult[JsValue] = (ch.\("paging").\("next")).validate[JsValue] val nextUrl: String = nextPage match { case s: JsSuccess[String] => s.get case e: JsError => null }
val nextPage: JsResult[JsValue] = (ch.\("paging").\("next")).validate[JsValue]
val nextUrl: String = nextPage match {
case s: JsSuccess[String] => s.get
case e: JsError => null
}
我有两个问题
Warning:(99, 19) non-variable type argument String in type pattern play.api.libs.json.JsSuccess[String] is unchecked since it is eliminated by erasure
case s: JsSuccess[String] => s.get
^
val nextUrl: String = nextPage match {
case s: JsSuccess[String] => s.toString
case e: JsError => null
}
java.lang.IllegalArgumentException: Illegal character in scheme name at index 9: JsSuccess(https://graph.facebook.com/v2.2/396697410351933/feed?limit=200&access_token=623501864400497%7CGumAg3k6Eu
JsValue
上调用validate[JsValue]
是毫无意义的,因为它总是会导致JsSuccess[JsValue]
。另一个问题是,您试图从JsSuccess[JsValue]
中对JsSuccess[String]
进行模式匹配,但由于许多原因,您无法这样做。首先,类型参数在运行时被清除,正如编译器警告所指出的那样。第二,JsSuccess[String]
不能是JsSuccess[JsValue]
,类型不相关
您真正需要的是验证[String]
不过,还有一种更优雅的方式。由于您似乎并不关心失败(您正在为
null
丢弃它们),因此您可以使用asOpt
。这里我要说的是,如果有可能没有next
,那么nextur
应该是Option[String]
,而不是String
,并且在Scala中永远不应该使用null
val nextUrl: Option[String] = (ch \ "paging" \ "next").asOpt[String]
如果出于某种原因必须使用null
:
val nextUrl: String = (ch \ "paging" \ "next").asOpt[String].getOrElse(null)