【问题标题】:How to convert JSON to a struct如何将 JSON 转换为结构
【发布时间】:2021-10-18 13:10:10
【问题描述】:

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

{"amount":1.0282E+7}

当我想转换它时出现错误:

Blocjson:无法将数字 1.0282E+7 解组到 Go 结构字段 MiddleEastAccountToCardResponse.amount 类型的 int64

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

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

【问题讨论】:

标签: json go marshalling


【解决方案1】:

修改你的代码如下:

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}

【讨论】:

    【解决方案2】:
    结构中的

    Amount 字段是 int64,但您尝试从字符串中解析的数字是 float(以科学记数法表示) .

    试试这个:

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

    【讨论】:

    • 它应该是float32或float64如果你声明为float它会抛出一个未定义的错误
    【解决方案3】:

    由于您没有解释您想要的确切结果,我们只能猜测。但是您有三种通用方法:

    1. 解组为浮点类型而不是整数类型。如果您需要 int,您也许可以稍后转换为 int。

    2. 解组为 json.Number 类型,该类型保留完整的 JSON 表示形式及其精度,并可根据需要转换为 int 或 float。

    3. 使用自定义解组器,它会为您从 float 转换为 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)
    }
    

    See it in the playground.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-22
      • 2021-08-07
      • 2015-02-05
      • 2021-12-10
      • 1970-01-01
      • 2018-11-07
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多