Jenkinsfile中Groovy调用API遇JsonSlurperClassic序列化异常求助
解决方案
问题根源
Jenkins Pipeline会序列化所有上下文变量以支持中断恢复,但JsonSlurperClassic、URLConnection这类对象本身不支持序列化,且你的代码存在两个小问题:
jsonSlurper未加def修饰,成为全局变量被Pipeline上下文捕获doOutPut拼写错误,应为doOutput
修复方案
将API调用逻辑封装在@NonCPS注解的方法中,该注解标记的代码不会被Jenkins序列化,可安全使用不可序列化对象:
pipeline { agent any stages { stage('Call API') { steps { script { def apiResponse = callApi("your-api-url-here") // 处理响应 echo "API Response: ${apiResponse}" } } } } } // 用@NonCPS包裹API调用逻辑 @NonCPS def callApi(String apiUrl) { def connection = new URL(apiUrl).openConnection() def jsonSlurper = new groovy.json.JsonSlurperClassic() connection.setRequestProperty("Content-Type", "application/json") connection.setRequestMethod("POST") connection.doOutput = true // 修正拼写错误 connection.connect() // 读取响应并解析 def responseText = connection.getInputStream().getText() def response = jsonSlurper.parseText(responseText) // 关闭流避免资源泄漏 connection.getInputStream().close() return response }
关键说明
@NonCPS方法内的所有对象仅存在于方法执行期间,不会被Pipeline序列化,彻底规避NotSerializableException- 确保所有变量都是方法内的局部变量,不暴露到Pipeline全局上下文
- 手动关闭输入流,避免资源泄漏
- 本地测试正常是因为本地Groovy环境不需要序列化上下文,而Jenkins Pipeline强制序列化
内容的提问来源于stack exchange,提问作者Kittles
相关产品推荐
相关产品推荐

