简体   繁体   中英

How to validate by JSON transformers?

I am using Play Framework 2.2.1 + Scala. I want to use JSON coast-to-coast design . But I don't understand how to validate incoming JSON.

For example I have some structure:

{
  name: "Alice",
  hobby: ["skiing", "biking", "smoking"]
}

And I need to check that hobby could contains only "skiing" , "biking" , but not "smoking" and name is not null . How can I check this?

Here is some code example to modify:

val transformer = (
  (__ \ 'name ).json.pickBranch and
  (__ \ 'hobby).json.pickBranch ) reduce

def add = Action(parse.json) { request =>
  request.body.validate(transformer).map{ js =>
    Ok("all right")
  }.recoverTotal{ e =>
    BadRequest("Detected error:"+ JsError.toFlatJson(e))
  }
}

I think the best way would to first define a regex pattern reader based on your requirement of "skiing or biking", then combine that to create the overall transformer:

val hobbyReads = Reads.pattern("skiing|biking".r)

val transformer = (
  (__ \ "name").read[String] and
  (__ \ "hobby").read(Reads.seq[String](hobbyReads))
) tupled

To actually read the json, I would recommend the fold function:

transformer.reads(request.body).fold(
  invalid => BadRequest(JsError.toFlatJson(invalid)),
  valid => Ok("all right")
)

Also. be mindful that if you're running any unit tests, make sure that you are using valid JSON (the one in your example is invalid as the keys are missing quotes and there's no comma separating the fields).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM