如何使用JsonSlurper?

时间:2015-12-22 08:20:59

标签: json groovy soapui jsonslurper

我在SOAP UI中编写了一个测试用例,它创建了一个用户并返回了Id。这是JsonResponse。通过Groovy脚本,我需要提取 id

{
    "schemas":["urn:hid:scim:api:ma:1.0:UserInvitation"],
    "urn:hid:scim:api:ma:1.0:UserInvitation":
        [
            {
                "meta":{ 
                    "resourceType":"UserInvitation",                                                   
                    "lastModified":"2015-12-22T07:45:30Z",
                    "location":"https://test-ma.api.assaabloy.com/credential-management/customer/663/invitation/2643209"
                },
                "invitationCode":"FBXO-SRWS-LKFI-ZKZI",
                "status":"PENDING",
                "createdDate":"2015-12-22T02:45:30Z",
                "expirationDate":"2015-12-22T02:45:30Z",
                "id":2643209
             }
         ]
}

我是Groovy的新手。请帮帮我。

1 个答案:

答案 0 :(得分:3)

它将是:

import groovy.json.JsonSlurper

def json = """
{
    "schemas":["urn:hid:scim:api:ma:1.0:UserInvitation"],
    "urn:hid:scim:api:ma:1.0:UserInvitation":
        [
            {
                "meta":{ 
                    "resourceType":"UserInvitation",                                                   
                    "lastModified":"2015-12-22T07:45:30Z",
                    "location":"https://test-ma.api.assaabloy.com/credential-management/customer/663/invitation/2643209"
                },
                "invitationCode":"FBXO-SRWS-LKFI-ZKZI",
                "status":"PENDING",
                "createdDate":"2015-12-22T02:45:30Z",
                "expirationDate":"2015-12-22T02:45:30Z",
                "id":2643209
             }
         ]
}"""
def slurped = new JsonSlurper().parseText(json)
assert 2643209 == slurped."urn:hid:scim:api:ma:1.0:UserInvitation"[0].id

new JsonSlurper().parseText(json)语句将返回map的实例。因此,使用此地图,您将获得包含此语句的列表:slurped."urn:hid:scim:api:ma:1.0:UserInvitation",然后使用getAt运算符([0])的第一个元素,最后使用id获得所需的值。