如何在Rest Assured框架中为嵌套JSON添加值?

时间:2018-07-24 20:32:38

标签: json groovy rest-assured

我有以下JSON响应块。我正在使用com.jayway.restassured.response.Response类从API读取响应。

{
    layouts:
    {
        regions:
        {
            [
                metadata: null, 
                endDate: null, 
                displayName: null, 
                roles: []
            ],  
            [
                metadata: null, 
                endDate: null, 
                displayName: null, 
                roles: []
            ]
        },
    }
}

我需要将以下结构添加到regions数组中:

[
    structure: 100, 
    type: 101, 
    widgets: [], 
    width: 12
]

这样生成的JSON看起来像这样:

{
    layouts:
    {
        regions:
        {
            [
                metadata: null, 
                endDate: null, 
                displayName: null, 
                roles: []
            ],
            [
                structure: 100, 
                type: 101, 
                widgets: [], 
                width: 12
            ],
            [
                metadata: null, 
                endDate: null, 
                displayName: null, 
                roles: []                   
            ]
        },
    }
}

做到这一点的最佳方法是什么?当我使用com.jayway.restassured.response.Response响应时,JSONSlurper似乎无法解析响应。还有其他想法吗?

1 个答案:

答案 0 :(得分:0)

您提供了正确的JSON响应吗?在正确的JSON中,“区域”应该是一个数组,例如:

{
    layouts:
    {
        regions:
        [
            {
                metadata: null, 
                endDate: null, 
                displayName: null, 
                roles: []
            },  
            {
                metadata: null, 
                endDate: null, 
                displayName: null, 
                roles: []
            }
        ],
    }
}

您可以将LAX类型用于JsonSlurper

def json = new JsonSlurper(type: JsonParserType.LAX).parseText(text)
JsonBuilder builder = new JsonBuilder()

List regionsList = json.layouts.regions
regionsList << [
        structure: 100,
        type: 101,
        widgets: [],
        width: 12
]

builder.layouts {
    regions(regionsList)
}

println JsonOutput.prettyPrint(builder.toString())

上面的代码产生下一个结果:

{
    "layouts": {
        "regions": [
            {
                "metadata": null,
                "endDate": null,
                "displayName": null,
                "roles": [

                ]
            },
            {
                "metadata": null,
                "endDate": null,
                "displayName": null,
                "roles": [

                ]
            },
            {
                "structure": 100,
                "type": 101,
                "widgets": [

                ],
                "width": 12
            }
        ]
    }
}