首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在Play中替换JSON值

如何在Play中替换JSON值
EN

Stack Overflow用户
提问于 2013-02-01 23:05:41
回答 3查看 15.4K关注 0票数 19

如何在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 =>
EN

回答 3

Stack Overflow用户

发布于 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之前的版本中添加了一个重复的字段,而不是替换现有的值)

票数 34
EN

Stack Overflow用户

发布于 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 =>
票数 2
EN

Stack Overflow用户

发布于 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
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14649141

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档