Issue
Unable to resolve the below error while trying to create a pipeline using a groovy script.
java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.EchoStep.message expects class java.lang.String but received class net.sf.json.JSONArray
#!groovy
import groovy.json.*
pipeline {
agent any
stages {
stage('Publish To Exchange') {
steps {
script{
def apiUrl = "https://something.com/login"
def payload = JsonOutput.toJson(["username":"username", "password":"password"])
def response = sh (returnStdout: true, script: "curl -s --fail -H \"Content-Type: application/json\" -X POST ${apiUrl} -d '${payload}' ").trim()
def parsedJson = readJSON text: response
def token = parsedJson.access_token
echo token
def props = readJSON text: sh(returnStdout: true, script: "curl -s --fail -H \"authorization: Bearer $token\" https://something.com/assets?search=my-api")
echo props //error, output empty array or array of objects
}
}
}
}
}
I get the error while printing props. I also tried the below but it failed too with the below error.
java.lang.ClassCastException: org.jenkinsci.plugins.workflow.steps.EchoStep.message expects class java.lang.String but received class java.util.ArrayList
....
def props = sh(returnStdout: true, script: "curl -s --fail -H \"authorization: Bearer $token\" https://something.com/assets?search=my-api")
def json = new JsonSlurper().parseText(props)
echo json
Any help is appreciated. Thanks
Solution
use echo (json as String)
or println json
diff between println
and echo
:
println is a method from groovy Object class - it accepts any object as input parameter, converts it to a string if needed, and prints the result.
echo is one of the basic steps of jenkins pipeline and it requires string as input. so, before using it to print non-string values - you have to convert them to string.
Answered By - daggett
Answer Checked By - Timothy Miller (JavaFixing Admin)