如何从Groovy中的json对象获取值

时间:2018-09-03 19:08:20

标签: groovy soapui

def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')   
    log.info RawRecordsDateRangeResponse

我的答复是:

{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}

这里我想从json响应键中获取值作为日期。

2 个答案:

答案 0 :(得分:1)

您的响应表示JSON文档,并将其存储在String类型的变量中。您可以使用groovy.json.JsonSlurper类进行解析。考虑以下示例:

import groovy.json.JsonSlurper

def RawRecordsDateRangeResponse = context.expand('${getRawRecordsForDateRange#Response}')

def json = new JsonSlurper().parseText(RawRecordsDateRangeResponse)

def url = json.'2018-09-03'

println url

输出:

https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json

答案 1 :(得分:1)

如果这只是所需的JSON消息的键而不是值,则可以使用类似以下内容的

import groovy.json.JsonSlurper

def rawRecordsDateRangeResponse = '''{"2018-09-03":"https://dhap-dconnect-telemetry-data-dev2.s3.amazonaws.com/ULT/d83350d2-af56-11e8-b612-0242ac11001118/temperature/raw-2018-09-03.json"}'''
def json = new JsonSlurper().parseText(rawRecordsDateRangeResponse)

def date = json.collect({it.key})
print date

这将产生[2018-09-03]