json - 无法在 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,它不起作用。
解决方案
使用StringWriter
代替ByteArrayOutputStream
然后JsonOutput.prettyPrint( stringWriter.toString() )
推荐阅读
- vba - 添加行,然后用集合中的数据填充这些行
- laravel - 带有 csrf 的 laravel GuzzleHttp 帖子
- oracle - oracle 光标 + FORALL 花费时间
- c# - 从 bin 文件夹而不是 MSTest 中的 ..\Out\... 运行单元测试
- php - 如何使用触发器记录更新更改?
- .net - 在我的 PowerShell FTP 脚本中转义 @ 字符
- selenium - Selenium Webdriver switchTo() 方法在 Chrome 75 中失败
- javascript - 单击输入标签会更改整个内容
- sql - SQL Concat 多列 + "|" 加入
- c++ - 如何将选项卡添加到我的选项卡控件(WIN32 API C++ GUI)