首页 > 解决方案 > 无法在 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()

卷曲响应很好,当我在控制台上打印响应,存储在变量中时,它会给出响应数据,因为我看到一些“/n”字符,它不是整洁的 json。当我将其写入文件时,我看不到任何新行和整洁的 json,我只看到一行中的键值格式数据。

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

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

def json = JsonOutput.toJson(out)

println new JsonBuilder(out).toPrettyString()

我错过了什么?

我正在尝试仅使用 groovy 库。

更新:

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

标签: jsongroovypretty-printgroovy-console

解决方案


使用StringWriter代替ByteArrayOutputStream

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


推荐阅读