Cannot unmarshal string into Go value of type int64

Solution 1:

This is handled by adding ,string to your tag as follows:

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

This can be found about halfway through the documentation for Marshal.

Please note that you cannot decode the empty string by specifying omitempty as it is only used when encoding.

Solution 2:

use json.Number

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

Solution 3:

You could also create a type alias for int or int64 and create a custom json unmarshaler Sample code:

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)

}