Request:
- With a Struct that can request data both String and Number.
Problem:
- Initially an api adds an order with input:
1 2 3 4 5 | { "identity": "225777777", "amount":"1000" } |
- Structure data:
1 2 3 4 5 | type Request struct { Identity string `json:"identity"` Amount string `json:"amount"` } |
- A new requirement is to use the above api to integrate with another client, the same business requirement except that the type of amount is Number .
1 2 3 4 5 6 7 8 9 10 | var js = []byte(` { "identity": "225777777", "amount":1000 } `) var req Request err := json.Unmarshal(js, &req) fmt.Println(err) |
=> error will appear
1 2 | json: cannot unmarshal number into Go struct field Request.amount of type string |
Handle:
- With the above requirements, an amount field with type is String, Number. Need to change type json.Number
1 2 3 4 5 | type Request struct { Identity string `json:"identity"` Amount json.Number `json:"amount"` } |
- With type json.Number, it is possible to convert request data both:
1 2 3 4 5 6 7 8 9 10 11 | { "identity": "225777777", "amount":"1000" } -- { "identity": "225777777", "amount": 1000 } |
- Then each type is different, just:
1 2 3 4 5 6 | fAmount, _ := req.Amount.Float64() fmt.Println("float:", fAmount) iAmount, _ := req.Amount.Int64() fmt.Println("amount:", iAmount) fmt.Println("string:", req.Amount.String()) |
Full source
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | package main import ( "encoding/json" "fmt" ) type Request struct { Identity string `json:"identity"` Amount json.Number `json:"amount"` } func main() { var input1 = []byte(` { "identity": "0335888888", "amount":"1000" } `) var req Request err := json.Unmarshal(input1, &req) fmt.Println("err type String", err) fmt.Println("req1:", fmt.Sprintf("%#v", req)) fAmount, _ := req.Amount.Float64() fmt.Println("float:", fAmount) iAmount, _ := req.Amount.Int64() fmt.Println("amount:", iAmount) fmt.Println("string:", req.Amount.String()) fmt.Println("---") fmt.Println("---") fmt.Println("request-2") var input2 = []byte(` { "identity": "0335888888", "amount": 1000 } `) var req2 Request err2 := json.Unmarshal(input2, &req2) fmt.Println("err type Number:", err2) fmt.Println("req1:", fmt.Sprintf("%#v", req2)) fAmount2, _ := req2.Amount.Float64() fmt.Println("float:", fAmount2) iAmount2, _ := req2.Amount.Int64() fmt.Println("amount:", iAmount2) fmt.Println("string:", req2.Amount.String()) } |
Thank you brother: https://t.me/OpenDevGolang join this group if you have questions.