Mar*_*eyn 0 json go amazon-web-services
作为我们正在构建的应用程序的一部分,其中一个流程步骤是一个AWS Lamda,它可以捕获发布请求并对其进行一些处理,然后再进行移动。它具有一个API网关请求作为触发器,并且此请求的主体将是JSON字符串。我在将JSON字符串解析为GoLang Object时遇到问题。这是我所拥有的:
捕获请求的功能:
func HandleRequest(ctx context.Context, event events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
log.Print(fmt.Sprintf("body:[%s] ", event.Body))
parseResponseStringToTypedObject(event.Body)
return events.APIGatewayProxyResponse{
StatusCode: http.StatusOK,
Body: "OK",
}, nil
}
Run Code Online (Sandbox Code Playgroud)
然后parseResponseStringToTypedObject函数:
func parseResponseStringToTypedObject(responseString string) {
b := []byte(responseString)
var resp SimpleType
err := json.Unmarshal(b, &resp)
if err == nil {
log.Print(fmt.Sprintf("Account Name: [%s]", resp.accountName))
} else {
log.Print(fmt.Sprintf("Could not unmarshall JSON string: [%s]", err.Error()))
}
}
Run Code Online (Sandbox Code Playgroud)
这是SimpleType结构:
type SimpleType struct {
accountName string `json:accountName`
amount int `json:amount`
}
Run Code Online (Sandbox Code Playgroud)
我打开了CloudWatch Logs(我的lamda登录到的地方),看到该event.Body属性中存在该主体,然后注销了未编组对象(resp.accountName)中的一个字段,我注意到该字段为空白。为什么是这样?这是请求的日志输出:
您的SimpleType结构在这里需要两件事...
1)这些属性必须是“公共”或“导出”的。这意味着它们需要以大写字母开头。
和
2)这些属性需要适当的标签来进行JSON的序列化和反序列化。例如,每个JSON标签被"
type SimpleType struct {
AccountName string `json:"accountName"`
Amount int `json:"amount"`
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
97 次 |
| 最近记录: |