0

I am trying to write a scala application for JSON validation. I have a Animals.scala class that defines the following:

case class Animals (id: Int, type: String, targets: String)

object Animals {

    implicit val reads: Reads[Animals] = (
           (JsPath \ "id").read[Int] and
           (JsPath \ "type").read[String] and
           (JsPath \ "targets").read[String])(Animals.apply _)

}

I have Application.scala where I have tried to validate an incoming JSON against the case class.

object Application extends Controller {

  // action for JSON validation
  def validateRequest = Action { implicit request =>
    // this will fail if the request body is not a valid json value
    val bodyAsJson = request.body.asJson.get

    bodyAsJson.validate[Animals] match {
      case success: JsSuccess[Animals] => {
        val id = success.get.id
        Ok("Validation passed! id is "+ id)
      }
      case JsError(error) => BadRequest("Validation failed!")
    }
  }

}

And finally here's my JSON input:

{
"id" : 1,
"type" : "domestic",
"targets": {
     "AND": [
         {
         "breed": ["greyhound", "dalmatian"]
         },
         {
         "NOT": {
             "color": ["amber", "pale_amber", "black"]
             }
         },
        {
        "zipcode": ["90210", "90211"]
        }
    ]
 }
}

And I get the following error: JsError(List((/targets,List(ValidationError(error.expected.jsarray,WrappedArray())))))

I do realize that the error is thrown because targets field is not as simple as a String compared to my JSON. How do I wrap it so that the validation passes? Should I do List[List[String]] or something along those lines?

0

1 Answer 1

1

If you don't care about the structure of targets read it as a JsObject. It will parse any internal structure that way.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! That passed the validation. How hard would it be if I were to validate the contents of targets too or what would be the right approach to do so?
implement classes and Reads for them so that they adhere to the structure of your json

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.