Play2 Json替换键

时间:2014-04-04 12:31:13

标签: json playframework-2.0 playframework-2.2

我在请求中收到JSON对象,是否可以在Play2中替换另一个键?

更改JSON:

{ "name" : "My name" }

例如:

{ "nameAndSurname" : "My name" }

我有更复杂的JSON。我可以使用JSON变换器吗?

我在这里使用Scala就是一个简单的例子:

val json = Json.obj("name" -> "My name")
json.transform() <======== ???

1 个答案:

答案 0 :(得分:0)

我认为这很简单。这是一个应该有所帮助的例子:

case class User(nameAndSurname: String, age: Int)

implicit val userReads: Reads[User] = (
  (JsPath \ "name").read[String] and
  (JsPath \ "age").read[Int]
)(User.apply _)

// controller
...
json.validate[User] match {
  case s: JsSuccess[User] => {
    val user: User = s.get
    // do something with user
  }
  case e: JsError => {
    // error handling flow
  }

}