如何将 JSON 转换为结构

我调用了第三方 API,并得到了以下 JSON:

{"amount":1.0282E+7}

当我想转换它时,我得到了一个错误:

Blocjson:无法将号码 1.0282E+7 取消到 Go 结构字段“中东帐户到卡响应”类型 int64 的金额

我想在Go中将此JSON转换为以下结构:

type Response struct {
    Amount int64 `json:"amount"`
    }


qq_笑_17
浏览 148回答 3
3回答

紫衣仙女

由于您没有解释您的确切期望结果,我们只能猜测。但是你有三种一般的方法:取消封送至浮点型类型而不是整数类型。如果需要 int,您可以稍后转换为 int。取消对类型的封送,该类型保留了完整的 JSON 表示形式及其精度,并且可以根据需要转换为 int 或浮点数。json.Number使用自定义取消封口,它可以为您从浮点型转换为 int 类型。下面演示了这三个:package mainimport (    "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 int64func (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)}

拉风的咖菲猫

结构中的“数量”字段是 int64,但您尝试从字符串解析的数字是 float(在科学记数法中)。试试这个:type Response struct {     Amount float64 `json:"amount"`     }

沧海一幻觉

按如下方式修改代码:package mainimport (    "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}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go