2014-05-21 76 views
2

使用Spray.IO,我正在構建一個接收JSON輸入的服務。 我想通過檢查一些字段來驗證JSON有效負載。Spray.io驗證json指令

我沒有興趣在驗證JSON模式或解析錯誤,但檢查的字段值,而不是像真正的字段的類型(如:整數VS浮動)

我沒有興趣使用Scala的要求,因爲這會引發異常,並且不會通知客戶端所有在單個請求中發現驗證錯誤。

這是否有內置指令/拒絕?

我在Play中看到過類似的東西(http://www.playframework.com/documentation/2.2.1/ScalaJsonRequests),如果沒有內置的東西,我將如何去建立自己的東西?

回答

0

你可以在json編組的case類上使用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") 
} 

當您嘗試創建該類並且其中一個需求失敗時,您將得到一個異常。如果這是一個噴霧路線的一部分的反應將是400與身體requirement Failed: [failure message from the require statement that failed]

+0

謝謝@Gangstead爲你的答案。我剛剛編輯了我的問題,因爲我意識到你可能是一種有效的方法,但我會在我的請求中遺漏所有其他驗證錯誤。 – Roman

0

針對更新的問題,檢查所有斷言,你可以發揮創意與您的要求聲明:

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 
}