簡體   English   中英

無法將字符串解組為 int64 類型的 Go 值

[英]Cannot unmarshal string into Go value of type int64

我有結構

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 的簡單方法。

這是通過將,string添加到您的標簽來處理的,string如下所示:

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

這可以在Marshal的文檔中找到。

請注意,您不能通過指定omitempty來解碼空字符串,因為它僅在編碼時使用。

使用json.Number

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

您還可以為 int 或 int64 創建類型別名並創建自定義 json unmarshaler 示例代碼:

參考

// 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)

}



已發送:{“id”:1}已收到:{“id”:“1”}

我們來解決這個問題。

你的情況是 - > http發布'localhost:8080 / users / blahblah'id = 1

將其更改為 - > http post'localhost:8080 / users / blahblah'id:= 1

不需要做“json:id,string”的事情,只需“json:id”即可。 祝好運!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM