Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to decode JSON with type convert from string to integer in Golang for non-local types?

Below is the actual struct type in aws go sdk elbv2 package. There are other parameters in this struct. I have kept only the necessary ones for simplicity.

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"`
}  

I need to decode a JSON string with integer number like:

{ "name": "test-tg", "port": "8080", "protocol": "HTTP" ,"vpcId": "vpc-xxxxxx"}

go code:

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)
    }
}

I'm getting the below output, (if I pass port in integer format it'll work)

{
    Name: "testTG",
    Port: 0,
    Protocol: "HTTP",
    VpcId: "vpc-0f2c8a76"
}

My question is there is no json field in the original struct, so whatever valid name I pass as json field, it is still maaping to go field. i.e. I can send Name field as

"name, Name, NamE, etc" 

in json and it still works.

I'm confused here. For other user defined struct it wont map properly if I don't provide valid json name as defined against that go field.

Also how do I convert Port to integer from string during Json Unmarshlling?

As of now I'm using the exact copy of the struct in my project and removing the string type to integer for all integer type fields (also removed all pointers from all struct fields) and receiving the json object and I'm then converting it to integer and making the object of original struct.

It takes more time for me to maintain the exact copy by doing some changes in my project folder and to do validation against all such parameters.

I have the following questions.

  1. Is there a way to convert string to integer during unmarshlling without adding json tag like (json:",string") against the integer field.
  2. Is it a good practice to maintain an exact copy of the struct (struct of elbv2 package) with few changes?
like image 294
k_vishwanath Avatar asked Jan 03 '23 17:01

k_vishwanath


1 Answers

To convert from string to int64 simply tell Go that its a string encoded 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"`
}

from: https://golang.org/pkg/encoding/json

like image 60
Jonathan R Avatar answered Jan 05 '23 16:01

Jonathan R