Scala播放JSON组合器以验证相等性 [英] Scala play json combinators for validating equality

查看:76
本文介绍了Scala播放JSON组合器以验证相等性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用play 2.2.0 Reads验证我的应用程序中的传入请求.

I'm using play 2.2.0 Reads for validating incoming request in my application.

我正在尝试使用json API实现一个非常简单的事情. 我有一个像这样的json:

I'm trying to implement a very simple thing with json API. I have a json like this:

{
  "field1": "some value",
  "field2": "some another value"
}

我已经有Reads可以检查其他内容,例如最小长度

I already have Reads that checks for other stuff like minimal length

case class SomeObject(field1: String, field2: String)
implicit val someObjectReads = (
  (__ \ "field1").read(minLength[String](3)) ~
  (__ \ "field2").read(minLength[String](3))
)(SomeObject)

我想创建一个解析器组合器,该组合器将匹配两个字段的值,如果值相等则返回JsSuccess,否则返回JsError并将其与现有的Reads组合.

I want to create a parser combinator that will match values of two fields and return JsSuccess if values are equal and otherwise JsError and combine it with existing Reads.

我该如何实现?

更新:澄清了问题并更改了代码.

UPDATE: clarified the question and changed the code.

推荐答案

您可以使用filter对已解析的值进行进一步的验证:

You can use filter to do further validation on parsed values:

import play.api.data.validation._
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.libs.json.Reads._

case class SomeObject(field1: String, field2: String)
implicit val someObjectReads = (
  (__ \ "field1").read(minLength[String](3)) ~
  (__ \ "field2").read(minLength[String](3))
)(SomeObject).filter(
  ValidationError("field1 and field2 must be equal")
) { someObject =>
  someObject.field1 == someObject.field2
}

如果要针对每个字段列出错误消息,则必须使用flatMap,例如:

If you want the error message to be listed against each field, then you'll have to use flatMap, eg:

implicit val someObjectReads = (
  (__ \ "field1").read(minLength[String](3)) ~
  (__ \ "field2").read(minLength[String](3))
)(SomeObject).flatMap { someObject =>
  Reads { _ =>
    if (someObject.field1 == someObject.field2) {
      JsSuccess(someObject)
    } else {
      JsError(Seq(
        JsPath("field1") -> Seq(ValidationError("field1 and field2 must be equal")),
        JsPath("field2") -> Seq(ValidationError("field1 and field2 must be equal"))
      ))
    }
  }
}

这篇关于Scala播放JSON组合器以验证相等性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆