How to replace a JSON value in Play

后端 未结 5 1884
遥遥无期
遥遥无期 2020-12-31 01:58

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

def newReport() = Action(parse.json) { request =>
    var json = request.bod         


        
5条回答
  •  一生所求
    2020-12-31 02:34

    One approach is, as Marc B says, convert the JSON to something like a case class, manipulate that, and then create a new JSON.

    However you can also use JSON 'transformers'. Effectively what you do is build a Reads[SomeThing] object. This object is passed to the transform method which you call on your JSON object. It will change the JSON object and return a Success(result) or Failure(error) where result is the new modified JSON. Here's a (comparatively)very simple example:

    using json of format: {key -> value}

    def jsonXForm(value: String) = (__ \ "customerId").json.update(
      (__ \ "customerId").json.put(JsString(value))
    )
    json.transform(jsonXForm(yourNewValue)) match {...}`
    

    There is a decent guide here

提交回复
热议问题