2

使用 Spray.IO,我正在构建一个接收 JSON 输入的服务。我想通过检查它的一些字段来验证 JSON 有效负载。

我对验证 JSON 模式或解析错误不感兴趣,而是检查字段值,而不是像字段的真实类型一样(即:整数 vs 浮点数)

我对使用 Scala require不感兴趣,因为这会引发异常,并且无法通知客户端在单个请求中发现的所有验证错误。

对此是否有内置指令/拒绝?

我在 Play ( http://www.playframework.com/documentation/2.2.1/ScalaJsonRequests ) 中看到过类似的东西,如果没有内置任何东西,我将如何自己构建一些东西?

4

2 回答 2

0

您可以在 json 编组到的案例类上使用 Scala 的 require 。例子:

case class AccountSearchQuery (lookupType:Int, lookupValue:String) {
  require(lookupType != 6 || (lookupType == 6 && lookupValue.toLong > 99999), "lookupValue must be a greater than 99999 for lookupType 6 (account number)") 
  require(!lookupValue.isEmpty(), "lookupValue cannot be empty")
}

当您尝试创建类并且其中一个要求失败时,您将收到异常。如果这是 Spray 路线的一部分,则响应将为 400,带有 bodyrequirement Failed: [failure message from the require statement that failed]

于 2014-05-21T18:34:39.947 回答
0

作为对检查所有断言的更新问题的回应,您可以通过 require 语句获得创意:

case class User(name: String) {
  require(testAll, allTestMessages)
  def test1 = name.length > 5
  def test1M = if(test1) "too short."  else ""

  def test2 = name.length > 10
  def test2M = if(test2) "also too short." else ""

  def testAll = test1 && test2
  def allTestMessages = test1M + test2M 
}
于 2014-05-21T19:42:33.030 回答