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.

  1. 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 ...

Get Groovy 2 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.