如何在Play中替换JSON值

问题描述:

如何在Play中替换JSON值?
代码说明:

How do I replace a value in a JSON value in Play?
Code to illustrate:

def newReport() = Action(parse.json) { request =>
    var json = request.body
    if((json \ "customerId").as[Int] == -1){
      // replace customerId after some logic to find the new value
    }
    json.validate[Report](Reports.readsWithoutUser).map {
      case _: Report =>

根据

According to the Play Documentation, JsObjects have a method ++ that will merge two JsObjects. So, when you have your new integer value, you simply need:

val updatedJson = json.as[JsObject] ++ Json.obj("customerId" -> newValue)

从Play 2.4.x开始,您可以使用+:

As of Play 2.4.x you can use +:

val updatedJson = json.as[JsObject] + ("customerId" -> newValue)

(注意:+方法已在2.1.x中添加,但向对象添加了重复字段,而不是替换2.4.x之前的版本中的现有值)

(NOTE: the + method was added already in 2.1.x but adds a duplicate field to the object instead of replacing the existing value in versions prior to 2.4.x)