仅通过播放验证 Json

Validation Only With Play Json

我想使用 PlayJson 只验证某些 json 的多个字段,而不是将其映射到自定义对象。我只关心验证标准的是或否答案。有可能以这种方式使用 PlayJson 吗?到目前为止,我有类似的东西,

val json = .....

val reads = (JsPath \ "foo").read[String](min(5)) and
      (JsPath \ "bar").read[String](max(10))

json.validate["I ONLY WANT TO VALIDATE NOT MAP"](reads) match {
  case s: JsSuccess => true
  case e: JsError => false
}

感谢 Stack Overflow 社区。

我们可以通过 Reads[(String, String)] 反序列化为元组,而不是通过 Reads[MyModel] 反序列化为案例 class 模型

import play.api.libs.json._
import play.api.libs.json.Reads._
import play.api.libs.functional.syntax._

val reads = (
  (JsPath \ "foo").read[String](minLength[String](5)) and
  (JsPath \ "bar").read[String](minLength[String](10))
).tupled

val json = Json.parse(
  """
    |{
    |  "foo": "abcde",
    |  "bar": "woohoowoohoo",
    |  "zar": 42
    |}
    |""".stripMargin)

json.validate(reads).isSuccess

输出

res0: Boolean = true

请注意我们在创建 reader 和 isSuccess 时如何调用 tupled 方法以从验证过程中获取布尔值。

https://scalafiddle.io/sf/JBjdt2Y/0