[Golang] Multiple Type In Struct

·

1 min read

Hello,

Currently I am implement a struct with 2 type String and Number.

Normally, there will be this error:

err type String json: cannot unmarshal string into Go struct field Request.amount of type float64

or

err type String json: cannot unmarshal number into Go struct field Request.amount of type string

Handle

But when you handle struct type json.Number

type Request struct {
    Amount   json.Number `json:"amount"`
}

we are handle type String and Number.

  • this is code example:
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())
}