Far*_*mor 17 json scala playframework-2.0 playframework-2.1
如何在Play中替换JSON值中的值?
代码说明:
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 =>
Run Code Online (Sandbox Code Playgroud)
Zei*_*yth 32
根据Play文档,JsObjects有一个++
合并两个JsObjects的方法.所以,当你有了新的整数值时,你只需要:
val updatedJson = json.as[JsObject] ++ Json.obj("customerId" -> newValue)
Run Code Online (Sandbox Code Playgroud)
从Play 2.4.x开始,您可以使用+
:
val updatedJson = json.as[JsObject] + ("customerId" -> newValue)
Run Code Online (Sandbox Code Playgroud)
(注意:该+
方法已在2.1.x中添加,但在对象中添加了重复字段,而不是替换2.4.x之前版本中的现有值)
大致如下:
val updatedJson = if((request.body \ "customerId").as[Int] == -1){
val newId = JsObject(Seq(("customerId",JsString("ID12345"))))
(request.body ++ newId).as[JsValue]
} else request.body
updatedJson.validate[Report](Reports.readsWithoutUser).map {
case _: Report =>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12200 次 |
最近记录: |