0
我想爲JSON驗證編寫一個scala應用程序。我有一個Animals.scala類定義以下內容:使用斯卡拉JSON驗證
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 _)
}
我有Application.scala,我試圖驗證傳入的JSON對案例類。
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!")
}
}
}
最後這裏是我的JSON輸入:
{
"id" : 1,
"type" : "domestic",
"targets": {
"AND": [
{
"breed": ["greyhound", "dalmatian"]
},
{
"NOT": {
"color": ["amber", "pale_amber", "black"]
}
},
{
"zipcode": ["90210", "90211"]
}
]
}
}
而且我得到以下錯誤: JsError(List((/targets,List(ValidationError(error.expected.jsarray,WrappedArray())))))
我認識到錯誤被拋出,因爲targets
字段不是那樣簡單一個String
相比,我的JSON。我如何包裝它以便驗證通過?我應該做List[List[String]]
還是按照這些方法?
謝謝!通過了驗證。如果我也要驗證「目標」的內容,或者採取什麼樣的正確方法,這會有多難? – summerNight
爲它們實現類和讀取,以便它們堅持你的json結構 –