【问题标题】:Cannot unmarshal string into Go value of type int64无法将字符串解组为 int64 类型的 Go 值
【发布时间】:2014-02-04 18:26:49
【问题描述】:

我有结构

type tySurvey struct {
    Id     int64            `json:"id,omitempty"`
    Name   string           `json:"name,omitempty"`
}

我确实 json.Marshal 在 HTML 页面中写入 JSON 字节。 jQuery 修改对象中的 name 字段并使用 jQueries JSON.stringify 和 jQuery 将字符串发送到 Go 处理程序对对象进行编码。

id 字段编码为字符串。

发送:{"id":1} 接收:{"id":"1"}

问题是 json.Unmarshal 无法解组该 JSON,因为 id 不再是整数。

json: cannot unmarshal string into Go value of type int64

处理此类数据的最佳方法是什么?我不想手动转换每个字段。我希望编写紧凑、无错误的代码。

行情还不错。 JavaScript 不适用于 int64。

我想学习用 int64 值中的字符串值解组 json 的简单方法。

【问题讨论】:

  • 有没有办法知道是哪个字段导致了问题?

标签: json go marshalling unmarshalling


【解决方案1】:

您还可以为 int 或 int64 创建类型别名并创建自定义 json unmarshaler 示例代码:

Reference

// StringInt create a type alias for type int
type StringInt int

// UnmarshalJSON create a custom unmarshal for the StringInt
/// this helps us check the type of our value before unmarshalling it

func (st *StringInt) UnmarshalJSON(b []byte) error {
    //convert the bytes into an interface
    //this will help us check the type of our value
    //if it is a string that can be converted into a int we convert it
    ///otherwise we return an error
    var item interface{}
    if err := json.Unmarshal(b, &item); err != nil {
        return err
    }
    switch v := item.(type) {
    case int:
        *st = StringInt(v)
    case float64:
        *st = StringInt(int(v))
    case string:
        ///here convert the string into
        ///an integer
        i, err := strconv.Atoi(v)
        if err != nil {
            ///the string might not be of integer type
            ///so return an error
            return err

        }
        *st = StringInt(i)

    }
    return nil
}

func main() {

    type Item struct {
        Name   string    `json:"name"`
        ItemId StringInt `json:"item_id"`
    }
    jsonData := []byte(`{"name":"item 1","item_id":"30"}`)
    var item Item
    err := json.Unmarshal(jsonData, &item)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("%+v\n", item)

}



【讨论】:

    【解决方案2】:

    使用json.Number

    type tySurvey struct {
        Id     json.Number      `json:"id,omitempty"`
        Name   string           `json:"name,omitempty"`
    }
    

    【讨论】:

    • 这是正确答案。接受的答案不起作用
    【解决方案3】:

    这是通过将,string 添加到您的标签来处理的,如下所示:

    type tySurvey struct {
       Id   int64  `json:"id,string,omitempty"`
       Name string `json:"name,omitempty"`
    }
    

    这可以在Marshal 的文档中找到。

    请注意,您不能通过指定 omitempty 来解码空字符串,因为它仅在编码时使用。

    【讨论】:

    • 如果id 没有以整数形式出现,这将起作用。否则,你会得到一个错误“invalid use of ,string struct tag...”
    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2021-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多