Forum Discussion
Below is a scripted example on taking the content of a payload in a POST request and routing the JSON nodes into a virtual response message. To read in the values of the request body I use the mockRequest.getRequestContent() method. This will return a string value that may include some extra content along with the request payload. You'll likely want to trim the extra content out so that the payload is extracted from the original string. Once we have the payload isolated, we can create a JSON slurper to easily extract the content of the JSON nodes. The nodes are then tied to a property value that I reference in the response message using the requestContext.value format, where value is the name of the property that we'll reference in the response.
//Add slurper to isolate json. This makes it easier to parse the nodes in the response
import groovy.json.JsonSlurper
//Save the response content to a string
//This will result in some overhead
def logText = mockRequest.getRequestContent()
// Find the index of the first '{' character
def startIndex = logText.indexOf('{')
// Extract the substring starting from the '{' character
def result = startIndex != -1 ? logText.substring(startIndex) : logText
//pipe the result into a json slurper for easy parsing
def jsonSlurper = new JsonSlurper()
def JsonBody = jsonSlurper.parseText(result)
//We can map the individual nodes from the Json object that we created previously
requestContext.id = JsonBody.id
requestContext.categoryID = JsonBody.category.id
requestContext.categoryName = JsonBody.category.name
requestContext.name = JsonBody.name
requestContext.status = JsonBody.status
The response will then look like this:
{
"Message": "Successfully read in payload",
"Values": {
"ID": "${id}",
"Category ID": "${categoryID}",
"Category Name": "${categoryName}",
"Name": "${name}",
"Status": "${status}"
}
}
The result should look like this:
Related Content
- 2 years ago
- 8 months ago
Recent Discussions
- 3 days ago