Modifying JSON messages
After we've got acquainted with a way to read existing JSON messages (see the Parsing JSON messages with JsonSlurper recipe) and create our own (see Constructing JSON messages with JsonBuilder recipe), we need to have the ability to modify the messages that flow through our system.
This recipe will show how straightforward it is to alter the content of a JSON document in Groovy.
How to do it...
Let's use the same JSON data located in the ui.json
file that we used in the Parsing JSON messages with JsonSlurper recipe.
First of all we need to load and parse the JSON file:
import groovy.json.* def reader = new FileReader('ui.json') def ui = new JsonSlurper().parse(reader)
Since the data is actually just a nested structure, which consists of Maps, Lists and primitive data types, we can use the same API we would use for collections to navigate and change JSON data.
Consider the following snippet of code, which changes and removes some bits of the original JSON message:
ui.items...