我有一个案例课:
case class ProfileUrl
(
profileId : Long,
socialUrl : String
)
implicit val profileUrlJsonFormat : Format[ProfileUrl] = Json.format[ProfileUrl]
我想验证
socialUrl
包含有效的URL。我正在考虑使用java.net.URL
或java.net.URI
。我不想在我从json实例化上述类时为需要运行的URL创建自定义验证器。有没有办法通过包装URL或创建自定义json解析器来做到这一点?无论哪种方式,我将如何去做类似的事情?
最佳答案
一种选择是使用URL regular expression和Reads.pattern
为socialUrl
字符串值定义正则表达式约束,如下所示:
import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._
case class ProfileUrl(
profileId : Long,
socialUrl : String
)
object ProfileUrl {
val urlRegex =
"""((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)""".r
implicit val profileUrlReads: Reads[ProfileUrl] = (
(JsPath \ "profileId").read[Long] and
(JsPath \ "socialUrl").read[String](pattern(urlRegex, "Malformed URL"))
)(ProfileUrl.apply _)
}
object UrlJsonValidationExample extends App {
val str = """{"profileId": 123, "socialUrl": "www.example.com"}"""
val json = Json.parse(str)
val profileUrl = json.as[ProfileUrl]
println(profileUrl)
}
关于java - 使用Java URI验证案例类中的url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50103849/