1. Overview

Serialization is a crucial concept when working with objects in any programming language. It’s the process of converting objects to a byte stream with a standard format that can be stored and transferred. This enables us to save the state of an object, transmit it, and reconstruct it again in a different destination system.

In this tutorial, we’ll cover how to serialize Groovy objects to a JSON string inside Jenkins pipeline.

2. Creating Groovy Object in Jenkins

Jenkins enables us to use native Groovy language scripts inside pipelines. This feature provides great flexibility to customize the pipeline flow and implement more complex scenarios. We can use the Groovy language in scripted pipelines or declarative pipelines inside a script block.

By using the Groovy language, we can create primitive data types and objects in our pipelines:

pipeline {
    agent any
    stages{
        stage("create groovy variable"){
            steps{
                script{
                    def student = ["name":"John", "age":20, "subjects":["English", "Math", "Physics"]]
                    echo "The variable type is ${student.getClass()}"
                    echo "The student name is ${student.name}"
                    echo "The student age is ${student.age}"
                    echo "The first subject is ${student.subjects[0]}"
                }
            }
        }
    }
}

Here we created a variable with the name student and a type of map, and we provided some key/value pairs for it. Then we print the class type of the variable using the getClass() method and print some of its values. Now let’s trigger our pipeline and see the output:

[Pipeline] echo
The variable type is class java.util.LinkedHashMap
[Pipeline] echo
The student name is John
[Pipeline] echo
The student age is 20
[Pipeline] echo
The first subject is English

As we can see, the variable class type is LinkedHashMap which is an implementation of the map interface. Then we can see the values that we defined in our map. So this is how we can simply define and work with Groovy variables inside a Jenkins pipeline.

3. Creating JSON Strings Using JsonOutput Class

Now if we want to convert our variable into a JSON string, we can use the native Groovy JsonOutput. The JsonOutput is a class for serializing Groovy objects to JSON strings. It’s part of the groovy.json package which contains different classes required for working with JSON.

The JsonOutput class contains a static toJson() method which takes a Groovy object as a parameter and returns a JSON string. So, let’s try this on our previous variable in the pipeline:

import groovy.json.JsonOutput
pipeline {
    agent any
    stages{
        stage("serialize groovy variable"){
            steps{
                script{
                    def student = ["name":"John", "age":20, "subjects":["English", "Math", "Physics"]]
                    def json_string = JsonOutput.toJson(student)
                    def json_pretty = JsonOutput.prettyPrint(json_string)
                    echo "${json_pretty}"
                }
            }
        }
        
    }
}

Here we first imported the JsonOutput class to use it in our script. Then we used the toJson() method and passed the student variable as a parameter. Finally, we formatted the JSON output using the prettyPrint() method to make it easier to read.

Now let’s check the output of this pipeline:

[Pipeline] echo
{
    "name": "John",
    "age": 20,
    "subjects": [
           "English",
           "Math",
           "Physics"
    ]
}

As we can see, the variable state is converted into a JSON string with all the key/value pairs. We can now store this JSON output in a file or database, or transmit it across the network.

4. Creating JSON Strings Using writeJSON Step

Another method to serialize a Groovy object into a JSON string is by using the writeJSON step. This is a native Jenkins step that we can use instead of relying on the groovy.json package or any of its classes. writeJSON is part of the pipeline utility steps plugin, so we need to install this plugin first to use this step:

Install pipeline utility steps plugin

After installing the plugin, we can use the writeJSON step inside the pipeline script to serialize our variable:

pipeline {
    agent any
    stages{
        stage("serialize groovy variable"){
            steps{
                script{
                    def student = ["name":"John", "age":20, "subjects":["English", "Math", "Physics"]]
                    def json_pretty = writeJSON(json: student, returnText: true, pretty: 4)
                    echo "${json_pretty}"
                }
            }
        }
        
    }
}

As we can see, the writeJSON step takes some parameters. The json parameter takes the name of the object that we need to convert to a JSON string, in this example, it’s the student variable. The returnText is a boolean that returns the JSON string as an output from the step instead of writing it to a file. The pretty parameter formats the output with the specified number of spaces for each indentation.

Now let’s check the output of this pipeline script:

[Pipeline] echo
{
    "name": "John",
    "age": 20,
    "subjects":     [
           "English",
           "Math",
           "Physics"
    ]
}

Again we can see the output is similar to the one we had when using the JsonOutput class. The writeJSON step converted the student variable into a JSON string with its state and values.

5. Conclusion

Serialization is a common process that we use to convert objects into a byte stream format. It enables us to store, transmit, and reconstruct the object’s state. Using Jenkins, we can define objects and variables in Groovy language inside pipelines.

In this article, we learned how to serialize these objects to JSON strings using the Groovy JsonOutput class, which we can import into our code. We can also use the native writeJSON step in Jenkins, which does the same thing, without relying on the Groovy packages and classes.