首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法将字符串解组为int64类型的Go值

问无法将字符串解组为int64类型的Go值
EN

Stack Overflow用户
提问于 2014-01-16 09:27:01
回答 3查看 95K关注 0票数 47

我有结构体

代码语言:javascript
复制
type tySurvey struct {
    Id     int64            `json:"id,omitempty"`
    Name   string           `json:"name,omitempty"`
}

我做json.Marshal写JSON字节在超文本标记语言页面。jQuery修改object中的name字段,并使用jQueries JSON.stringify对object进行编码,jQuery将字符串发布到Go处理程序。

编码为字符串的id字段。

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

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

代码语言:javascript
复制
json: cannot unmarshal string into Go value of type int64

处理这些数据的最佳方式是什么?我不希望手动转换每个字段。我希望写紧凑,无bug的代码。

Quotes还不算太差。JavaScript不能很好地与int64配合使用。

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

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2014-01-16 10:55:58

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

代码语言:javascript
复制
type tySurvey struct {
   Id   int64  `json:"id,string,omitempty"`
   Name string `json:"name,omitempty"`
}

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

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

票数 96
EN

Stack Overflow用户

发布于 2020-09-24 18:16:07

使用json.Number

代码语言:javascript
复制
type tySurvey struct {
    Id     json.Number      `json:"id,omitempty"`
    Name   string           `json:"name,omitempty"`
}
票数 14
EN

Stack Overflow用户

发布于 2021-04-25 15:46:45

您还可以为int或int64创建一个类型别名,并创建一个自定义的json解组程序示例代码:

Reference

代码语言:javascript
复制
// 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)

}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21151765

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档