playframework如何将表格映射到Map [String,String]

时间:2015-07-01 10:56:55

标签: playframework playframework-2.0

我有一个像

这样的课程
case class EventForm(name: String, attrs: Map[String, String])

我使用播放表格映射将json值转换为EventForm

 implicit val form = Form(
    mapping(
      "name" -> nonEmptyText,
      "attrs" -> of(mapFormatter)
       )(EventForm.apply)(EventForm.unapply) verifying logicConstraint
  )
像这样的mapFormatter:

implicit val mapFormatter = new Formatter[Map[String, String]] {
    override def bind(key: String, data: Map[String, String]): Either[Seq[FormError], Map[String, String]] = {
      stringFormat.bind(key, data).right.flatMap { value: String =>
//                  .either(Json.parse(value).as[Map[String, String]]))
//                  .left.map(e => Seq(FormError(key, "error.signedNumber", Nil)))
                Right(Json.parse(value).as[Map[String, String]])
      }
    }

    override def unbind(key: String, value: Map[String, String]): Map[String, String] = {
      Map(key -> Json.toJson(value).toString())
    }
  }

它编译好了,但是我会得到一个验证错误,例如"需要attrs"。

1 个答案:

答案 0 :(得分:0)

def mapFormat(errorMessage: String): Formatter[Map[String, String]] = new Formatter[Map[String, String]] {
def bind(key: String, data: Map[String, String]) = {
  val map = data
    .filterKeys(_.startsWith(s"$key."))
    .map(tuple => (tuple._1.substring(key.length + 1), tuple._2))

  val mapOpt = if (map.isEmpty) None else Some(map)
  mapOpt.toRight(Seq(FormError(key, errorMessage, Nil)))
}

def unbind(key: String, value: Map[String, String]) = Map(key -> Json.toJson(value).toString())

}

这里有点棘手,你可以尝试println(数据),然后你会明白为什么。