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 關注
- 136 瀏覽
添加回答
舉報