为了账号安全,请及时绑定邮箱和手机立即绑定

如何将 JSON 转换为结构

如何将 JSON 转换为结构

Go
qq_笑_17 2022-09-19 21:20:13
我调用了第三方 API,并得到了以下 JSON:{"amount":1.0282E+7}当我想转换它时,我得到了一个错误:Blocjson:无法将号码 1.0282E+7 取消到 Go 结构字段“中东帐户到卡响应”类型 int64 的金额我想在Go中将此JSON转换为以下结构:type Response struct {     Amount int64 `json:"amount"`     }
查看完整描述

3 回答

?
紫衣仙女

TA贡献1839条经验 获得超15个赞

由于您没有解释您的确切期望结果,我们只能猜测。但是你有三种一般的方法:

  1. 取消封送至浮点型类型而不是整数类型。如果需要 int,您可以稍后转换为 int。

  2. 取消对类型的封送,该类型保留了完整的 JSON 表示形式及其精度,并且可以根据需要转换为 int 或浮点数。json.Number

  3. 使用自定义取消封口,它可以为您从浮点型转换为 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)

}


查看完整回答
反对 回复 2022-09-19
?
拉风的咖菲猫

TA贡献1995条经验 获得超2个赞

结构中的“数量”字段是 int64,但您尝试从字符串解析的数字是 float(在科学记数法中)。

试试这个:

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



查看完整回答
反对 回复 2022-09-19
?
沧海一幻觉

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}


查看完整回答
反对 回复 2022-09-19
  • 3 回答
  • 0 关注
  • 147 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号