【问题标题】:playframework - Best way to trim a json valuesplayframework - 修剪 json 值的最佳方法
【发布时间】:2016-04-13 16:46:42
【问题描述】:

我正在尝试找出对即将到来的 json 进行 tim 值的最佳且优雅的方法。

例如,我有以下 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 _)
}

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

谢谢!

【问题讨论】:

    标签: json playframework-2.0 playframework-2.4


    【解决方案1】:

    map(_.trim) 用于read[String] 用于修剪字符串(通用解决方案)

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

    您也可以使用修剪后的字符串实现自己的 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 _)
    

    【讨论】:

    • 谢谢!这是我当前的解决方案..但我正在寻找一个更通用的解决方案..我有很多阅读,我可以从每个人那里解决这个问题,而不是将此映射添加到每一行。至少这是我希望达到的。
    【解决方案2】:

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

    object Someone {
    
      implicit val trimStringReads: Reads[String] = Reads.StringReads.map(_.trim)
    
      implicit val someoneReads: Reads[Someone] = Json.reads[Someone]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多