如何使用 aws api 网关的速度模板转换 json 中的数组?

How to transform array in json using velocity template for aws api gateway?

我一直在为 aws api-gateway 编写速度模板,以转换来自我的 api 的 json 响应,从而为用户提供一致的响应。

我一直在尝试转换这个 json:

{
    "amountCharges": [
        "charge1", "charge2", "charge3"
    ]
}

这个预期的:

{
    "charges": [
        "charge1", "charge2", "charge3"
    ]
}

我已经能够使用此模板为对象创建数组:

#set( $inputRoot = $input.path('$') )
"charges": [
    #foreach( $charge in $inputRoot.charges )
    {
        "type": "$charge.chargeType",
        "name": "$charge.chargeName",
        "amount": {
            "value": $charge.chargeAmount.amountValue,
            "currency": "$charge.chargeAmount.amountCurrency"
        },
        #if( $charge.chargeTax )
            "tax": {
                "name": "$charge.chargeTax.taxName",
                "amount": {
                    "value": $charge.chargeTax.taxAmount.amountValue,
                    "currency": "$charge.chargeTax.taxAmount.amountCurrency"
                }
            }
        #end
    }
    #if( $foreach.hasnext ) , #end
    #end
]

而此模板已经能够将我的 json 对象数组转换为所需的响应。下面提到的示例:

{         
    "charges": [
    {
        "chargeType": "someType1",
        "chargeName": "someName1",
        "chargeAmount": {
            "amountValue": 5,
            "amountCurrency": "someCurrency1"
        },
        "chargeTax": {
            "taxName": "someTax1",
            "taxAmount": {
                "amountValue": 5,
                "amountCurrency": "someCurrency1"
            }
        }
    },
    {
        "chargeType": "someType2",
        "chargeName": "someName2",
        "chargeAmount": {
            "amountValue": 10,
            "amountCurrency": "someCurrency2"
        }
    }
    ]
}

模板将此 json 转换为预期输出:

{
    "charges": [
    {
        "type": "someType1",
        "name": "someName1",
        "amount": {
            "value": 5,
            "currency": "someCurrency1"
        },
        "tax": {
            "name": "someTax1",
            "amount": {
                "value": 5,
                "currency": "someCurrency1"
            }
        }
    },
    {
        "type": "someType2",
        "name": "someName2",
        "amount": {
            "value": 10,
            "currency": "someCurrency2"
        }
    }
    ]
}

基本上,我想转换一个字符串数组,而不是键值对。任何线索都会有所帮助。提前致谢。

我这边只需要一个简单的调整:

#set( $inputRoot = $input.path('$') )
"charges": [
    #foreach( $amountCharge in $inputRoot.amountCharges )
        "$amountCharge"
        #if( $foreach.count < $inputRoot.amountCharges.size() ) , #end\
    #end
]