无法在 groovy 中转换为漂亮的字符串

Unable to convert into pretty string in groovy

我正在打 curl 电话以在 groovy 休息 api visa curl。响应很好,但响应非常大,是 17MB 的数据,以下是我的脚本:

def converter = "curl.......'"

def initialSize = 4096
def out = new ByteArrayOutputStream(initialSize)
def err = new ByteArrayOutputStream(initialSize)
def process = [ 'bash', '-c', converter].execute()
process.consumeProcessOutput(out, err)
process.waitFor()

Curl 响应正常,当我在控制台上打印响应并存储在变量 out 中时,它会提供不整齐的响应数据 json,因为我看到一些“/n”字符。当我将其写入文件时,我没有看到任何新行和整洁的 json,所有我看到的都是键值格式的一行数据。

{"key1":"value1","key2":"value2",} in one huge line only

这是我在 sublime 中观看的时候。现在我想将其转换为漂亮的 json 并整齐地写入 file.I 尝试遵循方法,但在控制台和文件中都打印为空 ({ })。

def json = JsonOutput.toJson(out)

println new JsonBuilder(out).toPrettyString()

我错过了什么?

我正在尝试仅使用 groovy 库。

更新:

当我尝试调试时,我发现这可能是因为所有 JSON 解析器都需要字符串,但我的输出是 ByteArrayOutputStream。但是现在我怎样才能将 out 转换为 string 呢?我试了 out.toString 和 out.text,都不行。

使用StringWriter代替ByteArrayOutputStream

然后JsonOutput.prettyPrint( stringWriter.toString() )