Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Complex JSON in Spring Cloud Contract Groovy contract

I've been trying to wrap my head around how to properly implement Spring Cloud Contract Verifier, but the JSON that I'm trying to enforce via the contract is complex, and I'm unsure how to handle it within the Groovy representation. The JSON body sometimes contains sub-objects of a key, sometimes it contains an array of objects.

    response {
    status(200)
    headers { contentType applicationJson() }
    body(
        "attrbte1": 777310402,    
        "attrbte2": 100,
        "attrbte3": "CAPSULE",
        "attrbte4": "01655",
        "attrbte5": "281604",
        "attrbte6": "28160420",
        "genericCodeNo": 16353,
        "stc": {
            "stcAttrbt1": 10000001600,
            "stcAttrbt2": "8875",
            "stcAttrbt3: "2008-08-04T00:00:00.000+0000",
            "stcAttrbt4": null
        },
        "gtc": {
            "gtcAttbt1": 10000000028,
            "gtcAttbt2": "0N",
            "gtcAttbt3": "2008-08-04T00:00:00.000+0000"
        },
        "etcs": [
            {
                "etcAttbt1": 530,
                "etcAttbt2": null,
                "etcAttbt3": null
            }
        ],
        "icds": [
            {
                "icdCode": "F31.3",
                "icdCode2": "F45.232"
            },
            {
                "icdCode": "F40.01",
                "icdCode2": "F44.2341"
            }
        ]
        )

Given that sub objects are curly braced, the groovy thinks that it's opening/closing a statement/operation, (kinda is...) but is part of the JSON body. I've tried the triple-single quote slash ('''/), but that treats the body as one contiguous string, without inspecting the individual attributes.

Question is really, is there an escape sequence that will ignore the curly braces, while preserving the hierarchical layout of the body.

like image 868
Andrew Reiplinger Avatar asked Oct 04 '18 15:10

Andrew Reiplinger


1 Answers

Use SQUARE BRACKETS to make objects (yes i know in JSON square brackets are for arrays, its weird, i didn't invent it)

You can surround field names with quotes or without, they both seem to work.

body([
    stringField1: value(regex(".*")),
    stringField2: value(regex(alphaNumeric()),
    innerObject1: [
        innerStringField1: "Hardcoded1",
        innerIntegerField1: anyInteger()
    ]
])

Wait? How do I make JSON lists then if square brackets are for objects?

Double square brackets. Seriously.

body(
    [[
        stringFieldOfObjectInList: regex(".*")
    ]]
)

How do I make a list of integers, like ids?

Honestly, haven't tried it yet. But i'm hoping if you don't have a field name inside the array, Spring CC will assume its a primitive and it will "just work".

like image 184
Bradleo Avatar answered Oct 12 '22 13:10

Bradleo