Jenkins Error - java.io.NotSerializableException: groovy.json.JsonSlurperClassic

1.1k views Asked by At

I am using Groovy trying to do an API call in a Jenkinsfile and trying to get a JSON response back. Here’s my code:

def url = “some url link”
def connection = new URL(url).openConnection()
jsonSlurper = new JsonSlurperClassic()
connection.setRequestProperty(“Content-Type”, “application/json”)
connection.setRequestMethod(“POST”)
connection.doOutPut = true
connection.connect()
def response = jsonSlurper.parseText(connection.getInputStream().getText())

If I just run this first piece of code, I get an error stating:

Caused: java.io.NotSerializableException: groovy.json.JsonSlurperClassic

I have tried using just JsonSlurper too, but also ran into the same error.

I tried to do an echo after each line above and looks like it’s having a hard time when doing the getInputStream part. I have tested this locally and it works fine. Any clue? Thanks!

2

There are 2 answers

0
grzegorzgrzegorz On

You should write it like this:

                script{
                   @NonCPS
                   def jsonSlurper = new groovy.json.JsonSlurper()
                   def result = jsonSlurper.parseText('{"key":"value"}')
                   echo result.key
                }

Jenkins says about NotSerializableException because this is what it just wants to do: to serialize, that is write your runtime code to disk. It can't do it with your code. Here is more info: https://www.jenkins.io/doc/book/pipeline/cps-method-mismatches/

However this decorator doesn't look elegant. You should try to use dedicated step for that purpose: https://www.jenkins.io/doc/pipeline/steps/pipeline-utility-steps/#readjson-read-json-from-files-in-the-workspace

                script{
                   def result = readJSON text: '{"key":"value"}'
                   echo result.key
                }
0
LongKang Fan On

The easiest way to solve this is to change the job configure: enter image description here