2017-10-06 165 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。