playframework - 修剪json值的最佳方法

时间:2016-04-13 16:46:42

标签: json playframework-2.0 playframework-2.4

我正试图找出一个最好和最优雅的方式来对待即将来临的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 _)
}

有没有办法在阅读时修剪json?或者我需要为此写一个变压器?如果我这样做,如何写它,这将是我将提供的每一个json的通用?

谢谢!

2 个答案:

答案 0 :(得分: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 _)

答案 1 :(得分:1)

您可以根据默认值指定自己的reads [String],然后使用宏:

object Someone {

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

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