Created
October 6, 2014 12:29
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.