JSON Handling of SQL NULL Values in Go
When working with nullable SQL data types in Go, the sql.Nullxxx types are often used to allow for null values. However, this can lead to formatting issues when encoding such structures into JSON using the json package.
By default, sql.Nullxxx types are marshaled as objects with an additional level due to their struct nature. This can result in undesired JSON output. To address this, consider implementing the json.Marshaller and json.Unmarshaler interfaces for a custom type that embeds the sql.Nullxxx type.
For example, the following JsonNullInt64 type can be used for encoding sql.NullInt64 values as null or integers:
type JsonNullInt64 struct { sql.NullInt64 } func (v JsonNullInt64) MarshalJSON() ([]byte, error) { if v.Valid { return json.Marshal(v.Int64) } else { return json.Marshal(nil) } } func (v *JsonNullInt64) UnmarshalJSON(data []byte) error { var x *int64 if err := json.Unmarshal(data, &x); err != nil { return err } if x != nil { v.Valid = true v.Int64 = *x } else { v.Valid = false } return nil }
When using the JsonNullInt64 type, it will be encoded in the expected manner, allowing for proper JSON representation without the additional level.
The above is the detailed content of How to Handle SQL NULL Values in Go JSON Marshalling?. For more information, please follow other related articles on the PHP Chinese website!