2017-10-06 172 views
0

我有以下的模板,我的作品怎麼指望它:Velocity模板解析無效JSON作爲有效的JSON

#set($allParams = $input.params()) 
{ 
    "body" : $input.json('$'), 
    "params" : { 
    #foreach($type in $allParams.keySet()) 
     #set($params = $allParams.get($type)) 
     "$type" : { 
     #foreach($paramName in $params.keySet()) 
      "$paramName" : "$util.escapeJavaScript($params.get($paramName))"#if($foreach.hasNext),#end 
     #end 
     }#if($foreach.hasNext),#end 
    #end 
    } 
} 

是什麼麻煩讓我看到這個模板仍然會解析無效JSON。

例如給定的轉換之前,以下無效JSON:

{ 
    "example": [email protected]#$%^&*()_+ 
} 

使用上面的模板,將其轉換爲:

{ 
    "body" : { 
     "asdasd": "[email protected]#$%^&*()" 
    }, 
    ... 
} 

我的問題是爲什麼呢? $input.json('$')不應該解析無效的JSON字符串嗎?

刪節日誌如下:

Execution log for request test-request 
Fri Oct 06 21:27:13 UTC 2017 : Starting execution for request: test-invoke-request 
Fri Oct 06 21:27:13 UTC 2017 : HTTP Method: POST, Resource Path: /equipment 
Fri Oct 06 21:27:13 UTC 2017 : Method request path: {} 
Fri Oct 06 21:27:13 UTC 2017 : Method request query string: {} 
Fri Oct 06 21:27:13 UTC 2017 : Method request headers: {} 
Fri Oct 06 21:27:13 UTC 2017 : Method request body before transformations: { 
    "asdasd": 123123$%^&*() 
} 
Fri Oct 06 21:27:13 UTC 2017 : Endpoint request body after transformations: { 
    "body" : {"asdasd":"123123$%^&*()"}, 
    "params" : { 
.... 
+0

什麼是輸入對象? – user7294900

+0

http://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-mapping-template-reference.html#input-variable-reference –

+1

然後問題出在Amazon API上,而不是Velocity,你應該在那裏提交一個錯誤報告。 –

回答

0

我能夠通過使用請求主體模式來解決我的問題:

{ 
    "$schema": "http://json-schema.org/draft-04/schema#", 
    "title": "Example", 
    "type": "object", 
    "required": [ 
     "example" 
    ], 
    "properties": { 
     "example": { 
      "type":"string" 
     } 
    } 
} 

所以API網關會檢查請求身體靠在JSON架構模型之上之前發送到Lambda。