如何在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 =>
发布于 2013-08-06 07:36:34
根据Play Documentation的说法,JsObjects有一个方法++
,它将合并两个JsObjects。因此,当您有了新的整数值时,您只需要:
val updatedJson = json.as[JsObject] ++ Json.obj("customerId" -> newValue)
从Play 2.4.x开始,您可以使用+
val updatedJson = json.as[JsObject] + ("customerId" -> newValue)
(注意: 2.1.x版本中已经添加了+
方法,但在2.4.x之前的版本中添加了一个重复的字段,而不是替换现有的值)
发布于 2013-02-08 08:31:05
大致是这样的:
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 =>
发布于 2014-09-21 18:44:58
我正在考虑摆脱所有那些不可变的"JSON“解决方案。这只会让代码变得一团糟。这是它在SON of JSON中的外观
import nl.typeset.sonofjson._
val json = …
if (json.customerId.as[Int] == -1) {
json.customerId = 987938
}
https://stackoverflow.com/questions/14649141
复制相似问题