3 回答

TA贡献1839条经验 获得超15个赞
由于您没有解释您的确切期望结果,我们只能猜测。但是你有三种一般的方法:
取消封送至浮点型类型而不是整数类型。如果需要 int,您可以稍后转换为 int。
取消对类型的封送,该类型保留了完整的 JSON 表示形式及其精度,并且可以根据需要转换为 int 或浮点数。
json.Number
使用自定义取消封口,它可以为您从浮点型转换为 int 类型。
下面演示了这三个:
package main
import (
"fmt"
"encoding/json"
)
const input = `{"amount":1.0282E+7}`
type ResponseFloat struct {
Amount float64 `json:"amount"`
}
type ResponseNumber struct {
Amount json.Number `json:"amount"`
}
type ResponseCustom struct {
Amount myCustomType `json:"amount"`
}
type myCustomType int64
func (c *myCustomType) UnmarshalJSON(p []byte) error {
var f float64
if err := json.Unmarshal(p, &f); err != nil {
return err
}
*c = myCustomType(f)
return nil
}
func main() {
var x ResponseFloat
var y ResponseNumber
var z ResponseCustom
if err := json.Unmarshal([]byte(input), &x); err != nil {
panic(err)
}
if err := json.Unmarshal([]byte(input), &y); err != nil {
panic(err)
}
if err := json.Unmarshal([]byte(input), &z); err != nil {
panic(err)
}
fmt.Println(x.Amount)
fmt.Println(y.Amount)
fmt.Println(z.Amount)
}

TA贡献1995条经验 获得超2个赞
结构中的“数量”字段是 int64,但您尝试从字符串解析的数字是 float(在科学记数法中)。
试试这个:
type Response struct { Amount float64 `json:"amount"` }

TA贡献1824条经验 获得超5个赞
按如下方式修改代码:
package main
import (
"encoding/json"
"fmt"
)
func main() {
var data = []byte(`{"amount":1.0282E+7}`)
var res Response
json.Unmarshal(data, &res)
fmt.Println(res)
}
type Response struct {
Amount float64 `json:"amount"`
}
输出:
{1.0282e+07}
- 3 回答
- 0 关注
- 147 浏览
添加回答
举报