playframework - trim json 值的最佳方式

playframework - Best way to trim a json values

我正在尝试找出最佳和优雅的方式来为即将到来的 json 计时值。

例如我有以下 json:

{
  "firstName": "   foo",
  "lastName": "bar    "
}

具有以下定义:

case class Someone(firstName:String, lastName: String)
object Someone{
  implicit val someoneReads: Reads[Someone] = (
      (JsPath \ "firstName").read[String] and
      (JsPath \ "lastName").read[String]
    )(Someone.apply _)
}

有没有办法在阅读时 trim json?或者我需要为此写一个变压器?如果我这样做,如何编写它以便我提供的每 json 次跳闸都是通用的?

谢谢!

使用map(_.trim) for read[String] for trim字符串(通用解决方案)

implicit val someoneReads: Reads[Someone] = (
    (JsPath \ "firstName").read[String].map(_.trim) and
      (JsPath \ "lastName").read[String].map(_.trim)
    )(Someone.apply _)

您也可以使用trimmed 字符串

实现自己的 Reads[String]
def trimmedString(path: JsPath): Reads[String] = Reads.at[String](path).map(_.trim)

implicit val someoneReads: Reads[Someone] = (
  trimmedString(JsPath \ "firstName") and trimmedString(JsPath \ "lastName")    
  )(Someone.apply _)

为了更熟悉的代码视图,您可以实现隐式转换

import scala.language.implicitConversions

class JsPathHelper(val path: JsPath) {
  def trimmedString: Reads[String] = Reads.at[String](path).map(_.trim)
}
implicit def toJsPathHelper(path: JsPath): JsPathHelper = new JsPathHelper(path)

implicit val someoneReads: Reads[Someone] = (
  (JsPath \ "firstName").trimmedString and
  (JsPath \ "lastName").trimmedString
)(Someone.apply _)

可以在默认的基础上指定自己的reads[String],然后使用宏:

object Someone {

  implicit val trimStringReads: Reads[String] = Reads.StringReads.map(_.trim)

  implicit val someoneReads: Reads[Someone] = Json.reads[Someone]
}