如何使用Groovy格式化文件中的json

时间:2017-01-03 23:25:09

标签: json groovy soapui

我有一个关于格式化文件的问题,以便它以正确的格式显示Json输出。

目前,我的代码将json导入文件,但是当我打开文件时,它会在一行中显示json(自动换行),如下所示:

{"products":[{"type":null,"information":{"description":"Hotel Parque La Paz (One Bedroom apartment) (Half Board) [23/05/2017 00:00:00] 7 nights","items":{"provider Company":"Juniper","provider Hotel ID":"245","provider Hotel Room ID":"200"}},"costGroups":[{"name":null,"costLines":[{"name":"Hotel Cost","search":null,"quote":234.43,"quotePerAdult":null,"quotePerChild":null}

我想格式化文件中的json,使其看起来像实际的json格式,如下所示:

{
  "products": [
    {
      "type": null,
      "information": {
        "description": "Hotel Parque La Paz (One Bedroom apartment) (Half Board) [23/05/2017 00:00:00] 7 nights",
        "items": {
          "provider Company": "Juniper",
          "provider Hotel ID": "245",
          "provider Hotel Room ID": "200"
        }
      },
      "costGroups": [
        {
          "name": null,
          "costLines": [
            {
              "name": "Hotel Cost",
              "search": null,
              "quote": 234.43,
              "quotePerAdult": null,
              "quotePerChild": null
            }

实际上每个标题都有自己的行来包含其值。

实现此目的的最佳方法是在文件中获取正确的json格式?

以下是代码:

    def groovyUtils = new com.eviware.soapui.support.GroovyUtils(context) 
    def dataFolder = groovyUtils.projectPath +"//Log Data//"
    def response = testRunner.testCase.getTestStepByName("GET_Pricing{id}").getProperty("Response").getValue();
    def jsonFormat = (response).toString()
    def fileName = "Logged At - D" +date+ " T" +time+ ".txt"
    def logFile = new File(dataFolder + fileName)


    // checks if a current log file exists if not then prints to logfile

    if(logFile.exists())
    {

     log.info("Error a file named " + fileName + "already exisits")
    }
        else
    {

     logFile.write "Date Stamp: " +date+ " " + time + "\n" + jsonFormat //response

1 个答案:

答案 0 :(得分:1)

如果你有一个现代版的groovy,你可以这样做:

JsonOutput.prettyPrint(jsonFormat)