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

  2. Consider the following snippet of code, which changes and removes some bits of the original JSON message:
    ui.items[0].type = 'panel'
    ui.items[0].title = 'Main Window'
    ui.items[0].remove('axes')
    ui.items[0].remove('series')
  3. The next step is to save the modified message. There is the groovy.json.JsonOutput class, which is designed specifically for that purpose. By using the static toJson and prettyPrint methods we can get an indented text version of the modified message:
    println JsonOutput.prettyPrint(JsonOutput.toJson(ui))
  4. Our initial modifications will lead to the following output:
    {
      "items": [
        {
          "title": "Main Window",
          "animate": true,
          "height": 270,
          "width": 319,
          "insetPadding": 20,
          "type": "panel"
        }
      ]
    }

How it works...

As we are operating on a Map, the code above does not do anything else but adding and removing Map entries.

The toJson method returns a String with a compact version of the JSON data. The prettyPrint method adds additional indentation spaces to any given JSON string.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.17.79.20