对于非本地类型,如何在 Golang 中使用类型从字符串转换为整数来解码 JSON?

k_v*_*ath 4 json go unmarshalling amazon-web-services

下面是 aws go sdk elbv2 包中的实际结构类型。此结构中还有其他参数。为了简单起见,我只保留了必要的。

type CreateTargetGroupInput struct {
    _ struct{} `type:"structure"`
    Name *string `type:"string" required:"true"`
    Port *int64 `min:"1" type:"integer" required:"true"`
    Protocol *string `type:"string" required:"true" enum:"ProtocolEnum"`
    VpcId *string `type:"string" required:"true"`
}  
Run Code Online (Sandbox Code Playgroud)

我需要用整数解码一个 JSON 字符串,例如:

{ "name": "test-tg", "port": "8080", "protocol": "HTTP" ,"vpcId": "vpc-xxxxxx"}
Run Code Online (Sandbox Code Playgroud)

去代码:

func main() {
    s := `{ "name": "test-tg", "port": "8080", "protocol": "HTTP" ,"vpcId": "vpc-xxxxxx"}`

    targetGroupInput := &elbv2.CreateTargetGroupInput{}
    err := json.Unmarshal([]byte(s), targetGroupInput)

    if err == nil {
        fmt.Printf("%+v\n", targetGroupInput)
    }
}
Run Code Online (Sandbox Code Playgroud)

我得到以下输出,(如果我以整数格式传递端口,它会工作)

{
    Name: "testTG",
    Port: 0,
    Protocol: "HTTP",
    VpcId: "vpc-0f2c8a76"
}
Run Code Online (Sandbox Code Playgroud)

我的问题是原始结构中没有 json 字段,所以无论我作为 json 字段传递的有效名称,它仍然是 maaping 去字段。即我可以将名称字段发送为

"name, Name, NamE, etc" 
Run Code Online (Sandbox Code Playgroud)

在 json 中,它仍然有效。

我在这里很困惑。对于其他用户定义的结构,如果我没有提供针对该 go 字段定义的有效 json 名称,它将无法正确映射。

另外,如何在 Json Unmarshlling 期间将端口从字符串转换为整数?

截至目前,我在我的项目中使用结构的精确副本,并将所有整数类型字段的字符串类型删除为整数(也删除了所有结构字段中的所有指针)并接收 json 对象,然后我将其转换到整数并制作原始结构的对象。

通过在我的项目文件夹中进行一些更改并针对所有此类参数进行验证,我需要更多时间来维护精确副本。

我有以下问题。

  1. 有没有办法在解组过程中将字符串转换为整数,而无需json:",string"针对整数字段添加像 ( )这样的 json 标记。
  2. 保持结构的精确副本(elbv2 包的结构)并且很少更改是一种好习惯吗?

Jon*_*n R 8

要将字符串转换为 int64,只需告诉 Go 它是一个编码为 int64 的字符串。

type CreateTargetGroupInput struct {
    _ struct{} `type:"structure"`
    Name *string `type:"string" required:"true"`
    Port *int64 `json:",string"`
    Protocol *string `type:"string" required:"true" enum:"ProtocolEnum"`
    VpcId *string `type:"string" required:"true"`
}
Run Code Online (Sandbox Code Playgroud)

来自:https : //golang.org/pkg/encoding/json