所以我尝试了一个嵌入了config.json文件的CI构建。Jenkinsfile - JsonSlurper返回一个字符串,而不是地图
config.json
{
"some_collection": [
{ "foo": "bar" }
]
}
我Jenkinsfile:
import groovy.json.JsonSlurper
node {
bootstrap()
test()
}
def bootstrap() {
stage('bootstrap') {
git([url: "[email protected]:my-user/my-jenkinsfile-repo.git"])
}
}
def test() {
def config = getConfig()
echo "${config}"
echo "${config.class}"
}
@NonCPS
def getConfig() {
new JsonSlurper().parseText(readFile("./config.json")))
}
配置对象的回波显示了JSON,因为它是在文件中,而config.class说是一个普通的老字符串。我期待的代码将返回一个地图。
我试过JsonSlurper和JsonSluperClassic,我也尝试过每种我能想到的方式来重构代码,使其更加明确,并且我的想法已经用完。
编辑:我尝试添加一些强类型:
def getConfig() {
JsonSlurper parser = new groovy.json.JsonSlurper()
def json = readFile("./config.json")
Map parsedJson = parser.parseText(json)
return parsedJson
}
这还是引起了config.class返回一个字符串
这是什么方法'readFile',它返回什么?你可以尝试用'new File(“./ config.json”)替换它。getText()'?您可以通过用'Map'替换'def'来在'getConfig()'声明中指定您期望的确切类。 –
新的File变体抛出了关于如何在Jenkins的上下文中不允许文件类的错误,我将尝试Map声明。 – DVG
你可以试着让你的'config'对象明确地指向'Map'吗? –