Home > Back-end >  json: cannot unmarshal number into Go struct field .Amount of type string
json: cannot unmarshal number into Go struct field .Amount of type string

Time:08-24

Trying to get balance of Tron wallet using tronscan.org

Sometimes Amount returns string, sometimes value like this

"amount": 1.4900288469458728E-8

When it returns value of this type i get this error json: cannot unmarshal number into Go struct field .Amount of type string

Here is my struct:

type trxResponse struct {
  Data []struct {
    Amount float64 `json:"amount,string"`
  } `json:"data"`
}

How can I handle it? To unmarshal json i'm using https://github.com/goccy/go-json

CodePudding user response:

As the amount field has different types, it can be declared as interface{} type, this will solve unmarshaling error.

type trxResponse struct {
  Data []struct {
    Amount interface{} `json:"amount"`
  } `json:"data"`
}

This can then be typecast from/to float64 or string as needed..

CodePudding user response:

You can implement the Unmarshaler interface by declaring custom UnmarshalJSON method, which will handle the amount field according to the type.


type trxData struct {
    Amount float64 `json:"amount"`
}

type trxResponse struct {
    Data []trxData `json:"data"`
}

// UnmarshalJSON custom method for handling different types
// of the amount field.
func (d *trxData) UnmarshalJSON(data []byte) error {
    var objMap map[string]*json.RawMessage

    // unmarshal json to raw messages
    err := json.Unmarshal(data, &objMap)
    if err != nil {
        return err
    }

    var amount float64 // try to unmarshal to float64
    if rawMsg, ok := objMap["amount"]; ok {
        if err := json.Unmarshal(*rawMsg, &amount); err != nil {
            // if failed, unmarshal to string
            var amountStr string
            if err := json.Unmarshal(*rawMsg, &amountStr); err != nil {
                return err
            }
            amount, err = strconv.ParseFloat(amountStr, 64)
            if err != nil {
                return err
            }
        }
    }

    d.Amount = amount

    return nil
}
  • Related