0
votes

How do I transform the JSON response body from -

{
    "data": [
      {
        "id": "1",
        "isEditable": false
      },
      {
        "id": "2",
        "isEditable": true
      }
      ]
}

To this -

{
    "data": [
{
        "id": "2",
        "isEditable": true
      }
      ]
}

How can we use .transformResponse here to do the same?

Any help will be much appreciated.

1

1 Answers

1
votes

Build the transformer like a function:

  (Session, Response) => Validation[Response]

For example:

  import io.gatling.http.response.{Response, StringResponseBody}
  import org.json4s._
  import org.json4s.jackson.Serialization.write
  import org.json4s.jackson.JsonMethods._

  implicit val formats: Formats = DefaultFormats

  case class Item(id: String, isEditable: Boolean)
  case class BodyResponse(data: List[Item])

  def transformFunction: (Session, Response) => Validation[Response] =
    (sess: Session, response: Response) => {
      val updatedBody = (parse(response.body.string)).extract[BodyResponse]
      response.copy(
        body = new StringResponseBody(
          write(updatedBody.copy(data = List(updatedBody.data.last))),
          Charset.forName("UTF-8")))
    }

and apply to the ProtocolBuilder:

http
.baseUrl("http://host") // Here is the root for all relative URLs
.transformResponse(transformFunction)

Note that I have used json4s which is included with Gatling and two types to parse and manipulate the response. You could query directly the Json without these types too.