如何在Play中替换JSON值 [英] How to replace a JSON value in Play

查看:126
本文介绍了如何在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)

这篇关于如何在Play中替换JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆