[英]json: cannot unmarshal number into Go struct field .Amount of type string
Trying to get balance of Tron wallet using tronscan.org尝试使用 tronscan.org 获取 Tron 钱包的余额
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
当它返回此类型的值时,我收到此错误
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
要解组 json 我正在使用https://github.com/goccy/go-json
As the amount field has different types, it can be declared as interface{}
type, this will solve unmarshaling error.由于 amount 字段有不同的类型,可以声明为
interface{}
类型,这样可以解决 unmarshaling 错误。
type trxResponse struct {
Data []struct {
Amount interface{} `json:"amount"`
} `json:"data"`
}
This can then be typecast from/to float64
or string
as needed..然后可以根据需要从/到
float64
或string
进行类型转换。
You can implement the Unmarshaler
interface by declaring custom UnmarshalJSON
method, which will handle the amount field according to the type.您可以通过声明自定义
UnmarshalJSON
方法来实现Unmarshaler
接口,该方法将根据类型处理金额字段。
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
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.