26

I created a method as shown online:

@NonCPS
def parseJsonString(String jsonString) {
    def lazyMap = new JsonSlurper().parseText(jsonString)

    // JsonSlurper returns a non-serializable LazyMap, so copy it into a regular map before returning
    def m = [:]
    m.putAll(lazyMap)
    return m
}

But I get the following error:

ERROR: java.io.NotSerializableException: groovy.json.internal.LazyMap

To work around this, I have to create an entire method to perform an entire step. For instance, in a method, I would do the same as above, parse the information I want, and finally return it as a string.

This, however, presents another issue, especially if you wrap this method inside a withCredentials, which would then require another withCredentials.

Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
Katone Vi
  • 1,010
  • 1
  • 8
  • 12

1 Answers1

59

I finally find a BETTER solution!

readJSON() method from the Jenkins "Pipeline Utility Steps" plugin as shown here:

https://jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

Here is a sample where we can finally ditch that ugly GROOVY JSONPARSE crap.

node() {
    stage("checkout") {
        def jsonString = '{"name":"katone","age":5}'
        def jsonObj = readJSON text: jsonString

        assert jsonObj['name'] == 'katone'  // this is a comparison.  It returns true
        sh "echo ${jsonObj.name}"  // prints out katone
        sh "echo ${jsonObj.age}"   // prints out 5
    }
}
Katone Vi
  • 1,010
  • 1
  • 8
  • 12
  • I keep trying different variations of this: `def props = readJson text: ` but even with the simple example string, I always get an error: `groovy.lang.MissingMethodException: No signature of method: Script1.readJSON() is applicable for argument types: (java.util.LinkedHashMap) values: ` – Max Cascone Mar 17 '21 at 19:28
  • 2
    Try `readJSON` not `readJson`. Make sure that the `Pipeline Utility Steps` plugin is installed. – Earl Ruby Nov 02 '21 at 20:37
  • this seems to fail when called from within a function, instead of a step. – mike01010 May 18 '23 at 05:00