Search code examples
scalaplay-json

Validation Only With Play Json


I'd like to use PlayJson to only validate multiple fields of some json and not map it to a custom object. I Only care about the Yes Or No answer to the validation criteria. Is it possible to use PlayJson in that way? So far I have something like,

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
}

Thank you Stack Overflow community.


Solution

  • Instead of deserialising to a case class model via Reads[MyModel] we can deserialise to a tuple via Reads[(String, String)] like so

    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
    

    which outputs

    res0: Boolean = true
    

    Note how we called tupled method when creating the reader, and isSuccess to get a boolean out of validation process.

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