如何在詹金斯文件中使用 groovy 读取对象数组或空数组?

How to read array of objects or empty array using groovy in jenkins file?

尝试使用 groovy 脚本创建管道时无法解决以下错误。

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

打印道具时出现错误。我也尝试了下面的方法,但它也因以下错误而失败。

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

感谢任何帮助。 谢谢

使用echo (json as String)println json


printlnecho 之间的差异:

println 是来自 groovy Object class 的方法 - 它接受任何对象作为输入参数,如果需要将其转换为字符串,并打印结果。

echo 是 jenkins 管道的基本步骤之一,它需要字符串作为输入。因此,在使用它打印 non-string 值之前 - 您必须将它们转换为字符串。