summerNight
summerNight

Reputation: 1506

JSON validation using Scala

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?

Upvotes: 0

Views: 964

Answers (1)

ValSmith
ValSmith

Reputation: 138

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

Upvotes: 1

Related Questions