可以使用groovy将JSON字符串格式转换为实际格式吗?

问题描述 投票:0回答:2

我从外部源获取以下JSON字符串格式: - 这实际上是什么样的格式?

{
id=102,
brand=Disha,
book=[{
   slr=EFTR,
   description=Grammer,
   data=TYR,
   rate=true,
   numberOfPages=345,
   maxAllowed=12,
   currentPage=345
   },
   {
   slr=EFRE,
   description=English,
   data=TYR,
   rate=true,
   numberOfPages=345,
   maxAllowed=12,
   currentPage=345
  }]
}

我想将其转换为实际的JSON格式,如下所示: -

{
"id": "102",
"brand": "Disha",
"book": [{
    "slr": "EFTR",
    "description": "Grammer",
    "data": "TYR",
    "rate": true,
    "numberOfPages": 345,
    "maxAllowed": "12",
    "currentPage": 345
    },
    {
    "slr": "EFRE",
    "description": "English",
    "data": "TYR",
    "rate": true,
    "numberOfPages": 345,
    "maxAllowed": "12",
    "currentPage": 345
   }]
}

这可以使用groovy命令或代码实现吗?

json rest groovy soapui ready-api
2个回答
1
投票

几件事:

  • 你不需要Groovy Script测试步骤,它目前作为step3
  • 对于step2,使用下面给出的脚本添加'Script Assertion`
  • 在下面的脚本中为nextStepName提供要添加请求的步骤名称。
//Provide the test step name where you want to add the request
def nextStepName = 'step4'

def setRequestToStep = { stepName, requestContent ->
    context.testCase.testSteps[stepName]?.httpRequest.requestContent = requestContent   
}

//Check the response
assert context.response, 'Response is empty or null'
setRequestToStep(nextStepName, context.response)

编辑:基于与OP在聊天中的讨论,OP希望更新步骤4的现有请求以获取密钥,并将其值更新为step2的响应。

使用样本来演示变更输入和所需输出。

让我们说,step2的回答是:

{ 
    "world": "test1"
}

而step4的现有请求是:

{
    "key" : "value",
    "key2" : "value2"
}

现在,OP希望在ste4的请求中通过第一个响应来更新key的值,并且期望的是:

{
    "key": {
        "world": "test1"
    },
    "key2": "value2"
}

这是更新的脚本,在Script Assertion中使用它来执行第2步:

//Change the key name if required; the step2 response is updated for this key of step4
def keyName = 'key'

//Change the name of test step to expected to be updated with new request
def nextStepName = 'step4'

//Check response
assert context.response, 'Response is null or empty'

def getJson = { str ->
    new groovy.json.JsonSlurper().parseText(str)
}

def getStringRequest = { json ->
    new groovy.json.JsonBuilder(json).toPrettyString()
}

def setRequestToStep = { stepName, requestContent, key ->
    def currentRequest = context.testCase.testSteps[stepName]?.httpRequest.requestContent
    log.info "Existing request of step ${stepName} is ${currentRequest}"
    def currentReqJson = getJson(currentRequest)
    currentReqJson."$key" = getJson(requestContent) 
    context.testCase.testSteps[stepName]?.httpRequest.requestContent = getStringRequest(currentReqJson)
    log.info "Updated request of step ${stepName} is ${getStringRequest(currentReqJson)}"   
}


setRequestToStep(nextStepName, context.request, keyName)

0
投票

我们可以使用以下代码将无效的JSON格式转换为有效的JSON格式: -

 def validJSONString = JsonOutput.toJson(invalidJSONString).toString()
© www.soinside.com 2019 - 2024. All rights reserved.