Skip to content

Instantly share code, notes, and snippets.

@smagch
Created October 6, 2014 12:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smagch/bc34f861df65c8ea2e90 to your computer and use it in GitHub Desktop.
Save smagch/bc34f861df65c8ea2e90 to your computer and use it in GitHub Desktop.
Custom sql.NullInt64 that handles json marshalling nicely, http://play.golang.org/p/w8VzxLGd-f
package main
import (
"database/sql"
"encoding/json"
"errors"
"log"
"strconv"
)
type Foo struct {
Id int `json:"id"`
WorkId NullInt64 `json:"work_id,omitempty"`
}
type NullInt64 sql.NullInt64
func (i *NullInt64) MarshalJSON() ([]byte, error) {
if !i.Valid {
return nil, nil
}
return []byte(strconv.Itoa(int(i.Int64))), nil
}
func (i *NullInt64) UnmarshalJSON(b []byte) error {
s := string(b)
if v, err := strconv.Atoi(s); err != nil {
i.Int64 = int64(v)
return nil
}
if s == "null" {
return nil
}
return errors.New("Invalid NullINt64: " + s)
}
func main() {
f := &Foo{100, NullInt64{100, true}}
b, err := json.Marshal(f)
if err != nil {
log.Fatal(err)
}
log.Println(string(b))
}
@valerykalashnikov
Copy link

valerykalashnikov commented May 24, 2017

According to this part of the spec https://golang.org/ref/spec#Type_declarations, your declared NullInt64 type alias does not inherit Scan() and Values() methods of sql.NullInt64 because sql.NullInt64 is not interface type.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment