将Jenkins构建结果写入JSON

时间:2014-01-14 13:39:06

标签: json groovy jenkins jenkins-plugins

我正在尝试使用Groovy的JsonBuilder和Groovy PostBuild插件创建Jenkins构建的JSON输出。除了构建结果之外,一切似乎都在起作用。它没有给我JSON输出中构建的实际结果,而是给了我一系列所有可能的结果(即SUCCESS,UNSTABLE,FAILURE等)。如果我只是将结果打印到控制台,它只打印实际结果。

以下是代码:

import groovy.json.*

def result = manager.build.result
manager.listener.logger.println result       // Prints just the build result

def json = new groovy.json.JsonBuilder()
def root = json.build {
    build_number manager.build.number
    build_timestamp manager.build.timestamp
    build_duration manager.build.duration 
    build_url manager.build.url
    build_project_name manager.build.project.name
    build_culprits manager.build.culprits
    build_result result                  // Prints an array of all possible results
    build_result manager.build.result    // Also prints an array of all possible results
}

manager.listener.logger.println "...and the status is ${result}"     // Prints just the   build result
manager.listener.logger.println JsonOutput.prettyPrint(json.toString())

这是输出:

UNSTABLE
...and the status is UNSTABLE
{
    "build": {
        "build_number": 85,
        "build_timestamp": "2014-01-14T13:26:06+0000",
        "build_duration": 0,
        "build_url": "job/JSON_Test/85/",
        "build_project_name": "JSON_Test",
        "build_culprits": [

        ],
        "build_result": {
            "names": [
                "SUCCESS",
                "UNSTABLE",
                "FAILURE",
                "NOT_BUILT",
                "ABORTED"
            ],
            "completeBuild": true
        }
    }
}

我已经为json.build块中的变量结果尝试了各种不同的语法组合,例如$ result,$ {result}和$ {result},但都会导致编译错误。

1 个答案:

答案 0 :(得分:1)

resulthudson.model.Result的一个实例,我认为它正在尝试序列化the whole class。您只希望String输出打印result类。

快速解决方法是:

def root = json.build {
    build_number manager.build.number
    build_timestamp manager.build.timestamp
    build_duration manager.build.duration 
    build_url manager.build.url
    build_project_name manager.build.project.name
    build_culprits manager.build.culprits
    build_result result.toString() // get the string representation
    // or:
    // build_result result.exportedObject
}